I have an object which contains multiple properties. For a given list of props in a 3rd object, I want to 'move' the properties from the original object and put them into a new object.
I have a 'longhand' way of doing this at the moment, something like the following. However this creates 2 new objects, rather than just 'moving' some of the keys out:
let pets = {
'cat': {},
'dog': {},
}
let animals = {
'cat': 'black',
'dog': 'white',
'whale': 'blue',
'albatross': 'grey',
}
let aPet = {}
let notAPet = {}
for (let [key, val] of Object.entries(animals)) {
if (key in pets) {
aPet[key] = val
} else {
notAPet[key] = val
}
}
Is there a nicer 'short' way of achieving the above, preferably only creating aPet while making animals end up equivalent to notAPet?
You can use delete operator:
let pets = {
'cat': {},
'dog': {},
}
let animals = {
'cat': 'black',
'dog': 'white',
'whale': 'blue',
'albatross': 'grey',
}
let aPet = {}
let notAPet = {}
for (let [key, val] of Object.entries(animals)) {
if (key in pets) {
aPet[key] = val
delete animals[key]
}
}
console.log(aPet, animals)