I have this object:
{
"clicked": 0,
"delivered": 0,
"effective": 0,
"enqueued": 0,
"errors": 0,
"forwarded": 0,
"read": 0,
"received": 0,
"recover_sent": 0,
"routing": 0,
"sent": 0
}
I want to split it into two object, the first one need to have 4 properties: received, errors, sent and delivered; the second one need to have the rest
Like this:
obj1 = {
"received": 0
"errors": 0,
"sent": 0
"delivered": 0,
}
obj2={
"clicked": 0,
"effective": 0,
"enqueued": 0,
"forwarded": 0,
"read": 0,
"recover_sent": 0,
"routing": 0,
}
If you don't mind creating temporary variables to store the values of keys, you can simply use destructuring assignment using the rest pattern.
const obj0 = {
"clicked": 0,
"delivered": 0,
"effective": 0,
"enqueued": 0,
"errors": 0,
"forwarded": 0,
"read": 0,
"received": 0,
"recover_sent": 0,
"routing": 0,
"sent": 0
}
const {received, errors, sent, delivered, ...obj2} = obj0;
const obj1 = {received, errors, sent, delivered};
console.log(obj1);
console.log(obj2);
Although I'd probably go the destructuring route, it's not clear whether the set of keys is known at build time.
You could achieve this with a dynamically acquired set of keys as follows:
const data = {
"clicked": 0,
"delivered": 0,
"effective": 0,
"enqueued": 0,
"errors": 0,
"forwarded": 0,
"read": 0,
"received": 0,
"recover_sent": 0,
"routing": 0,
"sent": 0
}
const obj1Keys = ["received", "errors", "sent", "delivered"];
const entries = Object.entries(data);
const obj1 = Object.fromEntries(entries.filter(([k]) => obj1Keys.includes(k)))
const obj2 = Object.fromEntries(entries.filter(([k]) => !obj1Keys.includes(k)))
console.log(obj1, obj2)
You may want to encapsulate krzysztof krzeszewski's answer in an anonymous function to avoid temp global variables:
const obj0 = {
"clicked": 0,
"delivered": 0,
"effective": 0,
"enqueued": 0,
"errors": 0,
"forwarded": 0,
"read": 0,
"received": 0,
"recover_sent": 0,
"routing": 0,
"sent": 0
};
const [ obj1, obj2 ] = (o => {
const { received, errors, sent, delivered, ...o2 } = o;
const o1 = { received, errors, sent, delivered };
return [ o1, o2 ];
})(obj0);
If you need to call it multiple times consider separating it in a dedicated and proper function (like "pick_and_separate(obj)").