skip to Main Content

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?

2

Answers


  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);
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search