I have an object:
const items = {
a: [3,5],
b: [6,7,8],
c: [0,10,1111]
}
and the array:
const existing = [3,8]
I'd like to create a new object, but without values that are included in the existing array. I mean this one:
const newItems = {
a: [5],
b: [6,7],
c: [0,10,1111]
}
Please about the tips!
CodePudding user response:
const items = {
a: [3,5],
b: [6,7,8],
c: [0,10,1111]
}
const existing = [3,8]
const result = Object.keys(items).reduce((acc, key ) => {
acc[key] = items[key].filter((item)=> !existing.includes(item))
return acc;
}, {})
console.log(result);
CodePudding user response:
You can use Object.entries
and Object.fromEntries
along with filter
to get the required result.
const items = {
a: [3, 5],
b: [6, 7, 8],
c: [0, 10, 1111],
}
const existing = [3, 8]
const newEntries = Object.entries(items).map(([key, value]) => [
key,
value.filter((x) => !existing.includes(x))
])
const newObject = Object.fromEntries(newEntries)