JavaScript: Comparing two objects - javascript

I want to compare two objects to make a new object.
original = [
{id: "A1", name: "Nick", age: 20, country: 'JP', code: 'PHP'}
]
edited = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", name: "Nick", age: 25, country: 'US', code: 'PHP'}
]
Compare two objects ('original' and 'edited')
If 'id' is set, compare the same ids' data, and take the data from 'edited', and get ONLY the 'id' and the data that is edited.
If 'id' is not set keep the whole data
The final object I want is like below;
final = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", age: 25, country: 'US'}
]
I've been trying this using filter, but I can't get desired result...

Try with Array#reduce .
Updated with all key pair match
Validate the edited array id value is available in original array using Array#map and indexOf function
If not push entire object to new array
First recreate the original array to object format like {key:[value]}
Then match each key value pair match or not with forEach inside the reduce function
var original = [{id: "A1", name: "Nick", age: 20, country: 'JP'}];
var edited = [{name: "Mike", age: 30, country: 'US'},{id: "A1", name: "Nick", age: 25, country: 'US'}];
var ids_org = Object.keys(original[0]).reduce((a,b,c)=> (a[b]=original.map(a=> a[b]),a),{});
var res = edited.reduce((a, b) => {
if (b.id) {
Object.keys(b).forEach(i=>{
if(ids_org[i].indexOf(b[i]) > -1 && i != 'id')
delete b[i];
})
a.push(b);
} else {
a.push(b);
}
return a;
}, []);
console.log(res)

use de structuring to extract out id from the object.
use lodash isEqual method to compare and later add back the id to the object.

Related

How do I convert an array of objects to an object of objects? [duplicate]

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 26 days ago.
For example, I have the following array of objects:
[{id:1, name: Hana, age: 30}, {id:2, name: Sana, age: 20}, {id:3, name: Kana, age: 30}]
I want to convert it to an object of objects as following:
{0:{id:1, name: Hana, age: 30}, 1:{id:2, name: Sana, age: 20}, 2:{id:3, name: Kana, age: 30}}
Using Object's pre built method assign you can achieve this.
Object.assign({}, yourObject);
No need to iterate through the Array unnecessary.
You can easily achieve the result, using a simple map function and store the result in an object as a key:value pair
const data = [{id:1, name: 'Hana', age: 30}, {id:2, name: 'Sana', age: 20}, {id:3, name: 'Kana', age: 30}]
const resultObj = {}
data.map((obj,index) => resultObj[index] = obj)
console.log(resultObj)
You can map that array and get its unique value (in this case i have taken id as key) then map it according you want to display array.
Here is an example to do that.
var arr = [{
id: 1,
name: 'Hana',
age: 30
}, {
id: 2,
name: 'Sana',
age: 20
}, {
id: 3,
name: 'Kana',
age: 30
}]
var mapped = arr.map(item => ({
[item.id]: item
}));
var newObj = Object.assign({}, ...mapped);
console.log(newObj);

How can I compare two arrays of objects and add new key to an objects in the second array

Given the following arrays and I'm asked to compare both arrays and return filtered array two with elements found in array one:
const array1 = [
{ name: "Jack", age: 54, title: "IT Engineer" },
{ name: "Josephine", age: 54, title: "chef" },
{ name: "Cortez", age: 34, title: "driver" }
];
const array2 = [
{ name: "Alex", age: 24, },
{ name: "Janvier", age: 24, title: "IT Engineer" }
];
The expected output is a new array that must verify if array two elements don't involve in array one
if array two-dot name is equal to array one dot name and array two doesn't have a key called title then
add title key in array two and set its value as 'none';
the expected output should look like this:
const result = [
{ name: "Alex", age: 24, title: "none" },
{ name: "Arsene", age: 24, title: "IT Engineer" }
];
Your two arrays don't correspond to a useful output based on your requirements
Stating them a bit clearer
If a value of the property name in array2 is not any of the values of the array elements of array1
then do not add the array2 element to the new array
If the value of the property name in array2 is in array1 AND the array element doesn't have the property title, add this to the array element.
Based on that criteria, you will get an empty array based on your arrays array1 and array2.
const array1 = [
{ name: "Jack", age: 54, title: "IT Engineer" },
{ name: "Josephine", age: 54, title: "chef" },
{ name: "Cortez", age: 34, title: "driver" }
];
const array2 = [
{ name: "Alex", age: 24, },
{ name: "Janvier", age: 24, title: "IT Engineer" }
];
const array1_Values = array1.map(elem => elem.name);
const newArray = array2.filter(elem => {
if (array1_Values.includes(elem.name) && !elem.hasOwnProperty('title')) {
elem.title = 'none';
return elem;
}
})
console.log(newArray); // Prints [] to console
To loop that we first need to loop the first array then find element with title in the second array and add the JSON key we want to add as well
array1.map(elem => {
const arr2WithTitle = arr2.find((data)=>data.name === elem.name);
return arr2WithTitle.title ? data.title =arr2WithTitle.title: arr2WithTitle.title = "none"
})

How can I convert an array of objects into an array of objects with the same values but with modified keys?

I have an array with objects and want to convert this to an array containing the same values but with different key names. (JavaScript)
For example, an array of
[{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}]
becomes
[{identification: "Bob", years: 50, person: true}, {identification: "Jerry", years: 20, person: true}]
Using the Map function works perfectly here.
const people = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
const formatted = people.map((person) => ({
identification: person.name,
years: person.age,
person: person.person
});
This should work for this problem.
I think that you may use the map method this method returns and array with the same length as the one you are mapping:
const array = [{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}];
let newKeysArray = array.map( a => {
let obj = {
identification: person.name,
years: person.age,
person: person.person
};
return obj
} );
So inside the map you are assigning the values that you need to a new object and return the object as the mapped item.
Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here:
let rows = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
let keyMaps = [
['name', 'identification'],
['age', 'years'],
];
for(let keyMap of keyMaps)
for(let row of rows)
delete Object.assign(row, {[keyMap[1]]: row[keyMap[0]] })[keyMap[0]];
console.log(rows);
keyMap[1] is the new key. keyMap[0] is the old key. Object.assign takes the value of the old key and places it in the new key. The delete keyword is confusing, but it doesn't apply to row as a whole. It's only deleting the old key.

How to edit object array?

I want to edit JavaScript object.
I have an JavaScript object like this
data_without_id = [
0: {id: 1, name: "Mary", age: null}
1: {id: 2, name: "Bob", age: 33}
2: {id: 1, name: "Kelly", age: 40}
]
I want to convert this object into this
data_without_id = [
0: {id: 1, name: "Kelly", age: 40}
1: {id: 2, name: "Bob", age: 33}
]
What I need to do is:
Group by id
Get latest value.
I tried using Array.prototype.reduce(), but I can't get the result I need...
Using the function reduce would be as follow:
The function reduce for grouping and the function Object.values for extracting the values.
let data_without_id = [ { id: 1, name: "Mary", age: null }, { id: 2, name: "Bob", age: 33 }, { id: 1, name: "Kelly", age: 40 }],
result = Object.values(data_without_id.reduce((a, {id, name, age}) => {
a[id] = {id, name, age};
return a;
}, Object.create(null)));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use .reduce by making the accumulator an object that has keys of the id. This way you can overwrite any previously seen objects which had the same id, and then use Object.values to get your array of objects:
const data_without_id = [{id: 1, name: "Mary", age: null}, {id: 2, name: "Bob", age: 33}, {id: 1, name: "Kelly", age: 40}],
res = Object.values(data_without_id.reduce((acc, obj) =>
(acc[obj.id] = obj, acc)
, {}));
console.log(res);
You could just simply use a for/of loop to create a copy of the data where the last object with a particular id will always be the object returned in the output data. This avoids the "grouping" part of the code but still returns the correct data.
const data_without_id = [
{ id: 1, name: "Mary", age: null },
{ id: 2, name: "Bob", age: 33 },
{ id: 1, name: "Kelly", age: 40 }
];
function lastId(arr) {
const out = [];
for (let obj of arr) {
// If you don't create a copy of each object the returned
// data will simply be contain _references_ to the original
// data. Changes in the original data will be reflected
// in the returned data
out[obj.id - 1] = { ...obj };
}
return out;
}
const lastIds = lastId(data_without_id);
console.log(lastIds);

ES6 Object Spread concat

I am new to object spread. I just knew object spread can be used to concat arrays . In below example i am concatenating variable a and address key. I want to know can we add address key value to each object of a array and get output as Required Output in code.
Can any one help me good reference to learn more on Object Spread.
var a = [{
'name':'jay',
age: 31
},
{
'name':'jay1',
age: 30
},
{
'name':'jay2',
age: 29
}];
var b = {...a, ...{address: 'add'}};
//b output
{name: "jay", age: 31}
{name: "jay1", age: 30}
{name: "jay2", age: 29}
address:"add"
// Required Output
{name: "jay", age: 31, address:"add"}
{name: "jay1", age: 30, address:"add"}
{name: "jay2", age: 29, address:"add"}
{ value:1, ...a, ...b, value:3 }
equals:
Object.assign({value:1}, a, b, {value:3})
In your case you need to do that for every element of your array:
const result = a.map(obj => ({...obj, address:"add"}));

Categories

Resources