Home > Net >  How to keep only one object in a nested object inside an array
How to keep only one object in a nested object inside an array

Time:05-05

I'm having an array look like this

 [
  { 
    object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1}
  },
  { 
    object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1}
  },
  { 
    object3:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1}
  },

 ]

Now i want to get rid of every nested item that have more than one item and keep only the first, like :

 [
  { 
    object1:{ childObj1:[grandChild1]}
  },
  { 
    object2:{ childObj2:[grandChild1]}
  },
  { 
    object3:{ childObj3:[grandChild1]}
  },

 ]

Which is the most effective way to do this?

CodePudding user response:

const arr = [{
    object1: {
      childObj1: ['grandChild1', 'grandChild2'],
      childObj3: 't',
      childObj2: 'r'
    }
  },
  {
    object2: {
      childObj1: ['grandChild1', 'grandChild2'],
      childObj3: 't',
      childObj2: 'r'
    }
  },
  {
    object3: {
      childObj1: ['grandChild1', 'grandChild2'],
      childObj3: 't',
      childObj2: 'r'
    }
  },

];

console.log(arr.map(el => {
  const child = el[Object.keys(el)[0]];
  const firstProperty = {
    [Object.keys(child)[0]]: child[Object.keys(child)[0]]
  };
  return {
    [Object.keys(el)[0]]: firstProperty
  }
}));

Hope this is what you wanted.

CodePudding user response:

Try this:

const o = [{
  a: [1, 1, 2, 3],
  b: {
    c: 'test',
    d: [1, 1, 3, 5, 3]
  }
}, {
  a: [1, 1, 2, 3],
  b: {
    c: false,
    d: []
  }
}];
console.log(f(o));

function f(obj) {
  for (let i in obj) {
    if (Array.isArray(obj[i])) {
      obj[i] = obj[i].slice(0, 1);
    } else if (typeof obj[i] === 'object') {
      obj[i] = f(obj[i])
    }
  }
  return obj;
}

  • Related