Bravo
Bravo

Reputation: 121

How to map new property to existing property in the array of objects JavaScript

I am trying to add the new property to the array of objects but while iterating, I am losing the existing values.

Is there any way, I can modify just the object's property and also do a null check?

I tried following.

const data = [
  {
    testid: 1,
    items: {
      id: 1,
      desc: 'test'
    }
  },
  {
    testid: 2,
    items: {
      id: 2,
      desc: 'test1'
    }
  },
  {
    testid: 3
  }
];

let result = data.map(({ items }) => ({
  ...items,
  newval: items?.id + ' - ' + items?.desc
}));
console.log(result);

//Expected Output

const newData = [
  {
    testid: 1,
    items: {
      id: 1,
      desc: 'test',
      newval: '1 -test'
    }
  },
  {
    testid: 2,
    items: {
      id: 2,
      desc: 'test1',
      newval : '2 -test1'
    }
  },
  {
    testid: 3
  }
];

Upvotes: 1

Views: 673

Answers (3)

Ori Drori
Ori Drori

Reputation: 191946

You need to clone the parent object of items as well, and then conditional clone the items sub object if one already exists:

const data = [{"testid":1,"items":{"id":1,"desc":"test"}},{"testid":2,"items":{"id":2,"desc":"test1"}},{"testid":3}];

const result = data.map(({ items, ...rest }) => ({
  ...rest, // clone the object
  ...items && { // clone the items and add the property if items exist
    items: {
      ...items,
      newval: items?.id + ' - ' + items?.desc
    }
  }
}));

console.log(result);

If you have an array of items instead of a single object, use another map:

const data = [ { testid: 1, items: [ { id: 1, desc: 'test' }, { id: 11, desc: 'test11' } ] }, { testid: 2, items: [ { id: 2, desc: 'test1' }, { id: 21, desc: 'test111' } ] }, { testid: 3 } ];

const result = data.map(({ items, ...rest }) => ({
  ...rest, // clone the object
  ...items && {
    items: items.map(item => ({
      ...item,
      newval: item?.id + ' - ' + item?.desc
    }))
  }
}));

console.log(result);

Upvotes: 3

symlink
symlink

Reputation: 12209

I think you're trying to simplify the code too much. Here is a more verbose version that I think is easier to read:

const data=[{testid:1,items:{id:1,desc:"test"}},{testid:2,items:{id:2,desc:"test1"}},{testid:3}];

let result = data.map(el => 
{
  if(el.items)
  {
    el.items.newval = `${el.items.id} - ${el.items.desc}`
    
    return {
      testid: el.testid,
      items: el.items
    }
  }
  else
  {
    return el
  }
})
console.log(result)

Upvotes: 0

brk
brk

Reputation: 50291

You need to expand items property

const data = [{
    testid: 1,
    items: {
      id: 1,
      desc: 'test'
    }
  },
  {
    testid: 2,
    items: {
      id: 2,
      desc: 'test1'
    }
  },
  {
    testid: 3
  }
];

let result = data.map((items) => ({
  ...items,
  items: {
    ...items.items,
    newval: items.items?.id + ' - ' + items.items ?.desc
  }
}));

console.log(result);

Upvotes: 1

Related Questions