0

I want to convert a list of objects into another in JS like

A = [{"id":"a", "name":"b", "email":"c"}, {"id":"c", "name":"d", "email":"c"}] to B = [{"id":"a", "value":"b"}, {"id":"c", "value":"d"}]

How to do this?

Sahil
  • 75
  • 2
  • 9

2 Answers2

1

This is just a simple re-mapping of id -> id and name -> value.

const
  arr = [{"id":"a", "name":"b", "email":"c"}, {"id":"c", "name":"d", "email":"c"}],
  res = arr.map(({ id, name: value }) => ({ id, value }));

console.log(res);

Here is a more-verbose version:

const
  arr = [{"id":"a", "name":"b", "email":"c"}, {"id":"c", "name":"d", "email":"c"}],
  res = arr.map(function (item) {
    return {
      id: item.id,
      value: item.name
    };
  });

console.log(res);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

You can use JavaScript's array method map to accomplish this.

Map iterates over each element of the array and returns an array.

const A = [{"id":"a", "name":"b", "email":"c"}, {"id":"c", "name":"d", "email":"c"}];

const res = A.map(item => {
  return {
    id: item.id,
    value: item.name,
  };
});

console.log(res)
ahsan
  • 1,409
  • 8
  • 11