Manju Prem
Manju Prem

Reputation: 69

How to create object id:name format in Reactjs

Currently in my application, I have some data contains id and name.

data = [
  {id: 1, name: 'user 1'}, 
  {id: 2 , name: 'user 2'}
]

I want to display in id:name format

{id: "name", id: "name" ....}
{1 : "user 1" , 2: "user 2" ...}

Upvotes: 1

Views: 1489

Answers (3)

Dokt
Dokt

Reputation: 199

In order to change that array of objects the way you want to, I would probably do it as follows:

let obj = {};
data.map(e => {
  obj[e.id] = e.name;
});

Hope it helps

Upvotes: -1

Avanthika
Avanthika

Reputation: 4182

You can use reduce to create the object this way

const array = [
 {id : 1,name : "user 1"}, {id :2 , name : "user 2"}
];
const object = array.reduce((o, s) => { 
   o[s.id] = s.name;
   return o;
}, {});
console.log(object);

Upvotes: 3

Tall Paul
Tall Paul

Reputation: 2450

You could loop through your data and transform it into a new object. This is how I would do it so the key is the id like your example and the value is the name. and if you want more properties set to the key you could even just set it to person instead of person.name.

data.reduce((hash, person) => {
  return hash[person.id] = person.name
}, {})

Here are the docs for the reduce method.

Upvotes: 0

Related Questions