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?
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?
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);
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)