How to merge 2 objects into one - javascript - javascript

I need help with solution on this. I have two objects:
Input:
obj1 = [{name:A}, {name:B}, {name:C}...,]
obj2 = [{value:1}, {value:2}, {value:3}...,]
And i need to make from these 2 objects one.
Output:
obj3 = [{A:1}, {B:2}, {C:3}...,]
Anybody know how to merge obj and obj2 to one? Thanks!

If you have consitent nameing, you could map with index.
const
names = [{ name: 'A' }, { name: 'B' }, { name: 'C' }],
values = [{ value: 1 }, { value: 2 }, { value: 3 }],
result = names.map(({ name }, i) => ({ [name]: values[i].value }));
console.log(result);

You could do this
const obj1 = [{name:'A'}, {name:'B'}, {name:'C'}];
const obj2 = [{value:1}, {value:2}, {value:3}];
const merged = Array.from({length:Math.min(obj1.length, obj2.length)}, (_,i) => {
return { [obj1[i].name]: obj2[i].value };
});
console.log(merged);

Related

Add new property to object if found in array

I have an array of objects and each object has an id. I have another array with id values. If an objects id is found in arrayOfIds, I would like to add new property called found and set to true. I was thinking of using findIndex as a possible function to use here.
const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const arrayOfIds = ['456']
Expected Output
const arrayOfObjects = [ { id: '123' }, { id: '456', found: true }, { id: '789' } ]
const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const arrayOfIds = ['456']
arrayOfObjects.map((object) => {
if(arrayOfIds.includes(object.id)) {
object.found = true;
}
})
console.log(arrayOfObjects);
I think it would make sense to convert your arrayOfIds to a Set to allow O(1) lookup.
const ids = new Set(arrayOfIds);
const augmentedObjects = arrayOfObjects.map(obj => {
if (ids.has(obj.id)) {
obj.found = true;
}
return obj;
});
You can create a Set from the array and use Array#map along with Set#has.
const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const ids = new Set(['456']);
const res = arrayOfObjects.map(o => ({...o, ...ids.has(o.id) && {found: true}}));
console.log(res);
You can map through the objects and spread the object with the found property.
const output = arrayOfObjects.map((obj) => {
if (arrayOfIds.includes(obj.id)) {
return { ...obj, found: true };
}
return obj;
});
You could do it by creating a lookup object. Create the lookup object from arrayOfIds and use that lookup object when traversing arrayOfObjects array and make certain changes.
const arrayOfObjects = [{ id: '123' }, { id: '456' }, { id: '789' }];
const arrayOfIds = ['456'];
const lookup = Object.fromEntries(arrayOfIds.map((x) => [x, { found: true }]));
const ret = arrayOfObjects.map((x) => ({ ...x, ...lookup[x.id] }));
console.log(ret);
Just run a map over the array of objects, and use the includes to add show: true by spreading the existing object else return the original object.
You could try something like this
const arrayOfObjects = [{ id: "123" }, { id: "456" }, { id: "789" }];
const arrayOfIds = ["456"];
const result = arrayOfObjects.map((item) => {
if (arrayOfIds.includes(item.id)) {
return {
...item,
found: true
};
}
return item;
});
console.log(result);

Make new object array from object in javascript [duplicate]

This question already has answers here:
Convert object to an array of objects?
(5 answers)
Closed 2 years ago.
i have object like:
let obj = {
type: 1
name: 'Test'
pr: 0
g: 1
}
and i wan't to make like this object with it:
obj = [
{
title: "type",
value: 1,
},
{
title: "name",
value: "Test",
},
{
title: "pr",
value: 0,
},
{ title: "gr", value: 1 },
];
so basically first key will be in name and second key will be value.
What i tried?
newObj = Object.keys(obj).forEach(function (key) {
obj = {
name: key,
value: key,
};
});
it's worked but it's give just first 2 value of the object and not makes object array.
so output is :
obj = {
name: type,
value: 1,
};
another entries not visible.
What i need to do ?
You can use Object.entries:
const obj = {
type: 1,
name: 'Test',
pr: 0,
g: 1
};
const res = Object.entries(obj)
.map(([title, value]) => ({title, value}));
console.log(res);
If you're not familiar with this syntax:
([title, value]) => ({title, value})
It could be rewritten as:
function (x) { return { title: x[0], value: x[1] }; }
But in the above example, I used a destructuring assignment to create 2 variables title and value from the provided key/value pair.
And {title, value} is just a shorthand syntax for { title: title, value: value }.
You can use Object.keys(...) and use map to get your desired result like below.
Object.keys(obj).map(x => ({ title: x, value: obj[x] }));
const obj = {
type: 1,
name: 'Test',
pr: 0,
g: 1
};
const res = Object.keys(obj).map(x => ({ title: x, value: obj[x] }));
console.log(res);
Also you can do this by reduce method with Object.keys(), as an alternative:
let obj = {
type: 1,
name: 'Test',
pr: 0,
g: 1,
}
const result = Object.keys(obj).reduce((acc, rec) => {
return [...acc, {
title: rec,
value: obj[rec]
}]
}, [])
console.log(result);

Lodash uniqWith, how say lodash keep last duplicate

Hello i'm using lodash uniqWith method for remove duplicated items which have same id in my array.
but lodash keep first duplicated item.
But i wan't to keep last duplicated item.
what can i do for that ?
var result = _.uniqWith(editedData, function(arrVal, othVal) {
return arrVal.id === othVal.id;
});
console.log(result)
You can create a uniqByLast function using _.flow(). Use _.keyBy() to get an object by id, and _.values() to get an an array:
const { flow, partialRight: pr, keyBy, values } = _
const lastUniqBy = iteratee => flow(
pr(keyBy, iteratee),
values
)
const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]
const result = lastUniqBy('id')(arr)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
And the same idea using lodash/fp:
const { flow, keyBy, values } = _
const lastUniqBy = iteratee => flow(
keyBy(iteratee),
values
)
const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]
const result = lastUniqBy('id')(arr)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
Easiest way? Reverse the array first (after cloning it to avoid mutation).
var result = _.uniqWith(_.reverse(_.clone(editedData)), function(arrVal, othVal) {...});
You can also simplify your code:
var result = _.uniqWith(_.reverse(_.clone(editedData)), ({ id: a }, { id: b }) => a === b);

How to get index of a 2d array of 2 similar structure ones with same value

Sorry the title may not present well.
I got two 2d arrays with similar structure.
array A:
arrayA[0]['account_name'] = 'a0';
arrayA[1]['account_name'] = 'a1';
arrayA[2]['account_name'] = 'a2';
And array B:
arrayB[0]['account_name'] = 'a1';
arrayB[1]['account_name'] = 'b0';
arrayB[2]['account_name'] = 'c0';
arrayB[3]['account_name'] = 'a0';
arrayB[4]['account_name'] = 'd3';
arrayB[5]['account_name'] = 'e8';
arrayB[6]['account_name'] = 'a3';
arrayB[7]['account_name'] = 'b4';
arrayB[8]['account_name'] = 'b1';
Now I know arrayA[0]['account_name'] equals to "a0", how can I search efficiently to check if it also exists in array B / know its position in array B? And I would like to loop for all values in array A.
const a = [
{ name: 'a0' },
{ name: 'a1' },
{ name: 'b2' }
];
const b = [
{ name: 'a0' },
{ name: 'a1' },
{ name: 'a2' },
{ name: 'b0' },
{ name: 'b1' },
{ name: 'b2' }
];
a.forEach((aa, i) => {
let found;
b.forEach((bb, j) => {
if(aa.name === bb.name) {
found = {
index: j,
value: aa.name
};
return true;
}
});
console.log(found);
});

Search an array for a property value that is contained in another array

I am trying to pull an object from an array of objects that's property value is contained in my other array.
const myArrayOfObjects = [
{ value: 'test1' }
{ value: 'test2' }
]
const myArray = [ 'test1', 'test5' ];
const pluckedValue = myArrayOfObjects.find((item) => {
let x;
myArray.forEach((include) => {
x = include === item.value ? include : undefined;
});
return item.value === x;
});
What I have works but it feels wrong. Is there a nicer way to accomplish this? Is this efficient? I have access to lodash and ES6 in my application.
You could just use a simple filter:
var result = myArrayOfObjects.filter(function (el) {
return myArray.includes(el.value);
});
var myArrayOfObjects = [
{ value: 'test1' },
{ value: 'test2' }
];
var myArray = ['test1', 'test5'];
var result = myArrayOfObjects.filter(function (el) {
return myArray.includes(el.value);
});
console.log(result);
This is the ES2015 way:
const myArrayOfObjects = [
{ value: 'test1' },
{ value: 'test2' }
];
const myArray = [ 'test1', 'test5' ];
const pluckedValue = myArrayOfObjects.filter(item => myArray.includes(item.value));
console.log(pluckedValue);
I would use a find function if you want a single value:
myArrayOfObjects.find(function(include){
return myArray.indexOf(include.value) !== -1;
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
One other way;
var myArrayOfObjects = [
{ value: 'test1'},
{ value: 'test2'}
],
myArray = [ 'test1', 'test5' ],
something = [];
for (var obj of myArrayOfObjects) myArray.includes(obj.value) && something.push(obj);
console.log(something);

Categories

Resources