Home > Software engineering >  Select subset of values from object and return new object
Select subset of values from object and return new object

Time:11-01

I have an array of objects, and I want to select a number of properties out from each one, creating a new object with those properties to return, as well as add a few more values to the new object. How can I do it better than this? I have also thought about having a list of properties to pull off of thing to make it easier. But looking for a better way. e.g.

        const a = things.map((thing) => {
            let {obj1, obj2, obj3} = thing;
            return {obj1, obj2, obj3, newVal: null, otherNewVal: null}
        });
        
        return a;

CodePudding user response:

You can exclude properties from thing that you don't want if there are less of them with:

        const a = things.map((thing) => {
            // thing = { obj1: {}, obj2: {}, obj3: {}, obj4: {}, obj5: {} }
            let {obj4, obj5, ...rest } = thing;
            // rest = { obj1: {}, obj3: {}, obj3: {} }
            return { ...rest, newVal: null, otherNewVal: null}
        });
        
        return a;

CodePudding user response:

You can avoid the repetition of the cherry-picked variable names like this:

const a = things.map(thing => (
  {...Object.fromEntries(Object.entries(thing).filter(([k,v])=>
  ['obj1','obj2','obj3'].some(i=>i===k))),
  newVal: null, otherNewVal: null
}));
  • Related