I am merging data from two arrays of objects based on a common property URL
and url
and I am using spread operator to add all the properties on the final array.
The problem is that if the common property value
does not have the same key
name, it will add "twice" that property, other than changing the property name or adding the properties one by one is there a way to exclude that property using spread operator.
const data1 = [{
url: 'google.com',
private: 'no'
},{
url: 'duckduckgo.com',
private: 'yes'
}]
const data2 = [{
URL: 'google.com',
many: true,
other: true,
properties: true,
dont: true,
want: true,
to: true,
add: true,
onebyone: true,
}]
const res = data2.map(obj => {
const otherData = data1.find(({ url }) => url === obj.URL)
return {
...obj,
...otherData
}
})
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }
The expected result would be to remove the 'duplicate' URL property and have just url: google.com
CodePudding user response:
Well, why don't you just remove the URL -field from the outcome?
const res = data2.map(obj => {
const otherData = data1.find(({ url }) => url === obj.URL)
const result = {
...obj,
...otherData
};
delete result.URL;
return result;
})
CodePudding user response:
As noted by OP in comments,
could you use my example and provide and anwser please
Please find below a working example. I think it's self-explanatory; however, if any questions, please post and will explain as needed.
const data1 = [{
url: 'google.com',
private: 'no'
},{
url: 'duckduckgo.com',
private: 'yes'
}]
const data2 = [{
URL: 'google.com',
many: true,
other: true,
properties: true,
dont: true,
want: true,
to: true,
add: true,
onebyone: true,
}]
const res = data2.map(({ URL, ...rest }) => {
const otherData = data1.find(({ url }) => url === URL)
return {
...rest,
...otherData
}
})
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }
NOTE: Instead of obj
we de-structure and access URL
and rest
. Then, when populating we simply skip URL
and keep only rest
. That's it.