ZahraPoorsoltani
ZahraPoorsoltani

Reputation: 3

How can I remove the name field from a json array?

I have a json array like this:

(3) [{…}, {…}, {…}]
0: {Id: 1, Name: "bask"}
1: {Id: 2, Name: "voll"}
2: {Id: 3, Name: "badminton"} 

I want to turn it into something like this:

{1:"bask",2:"voll",3:"badminton"}

Upvotes: 0

Views: 383

Answers (6)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

Using Array.reduce() :

var arr = [{
	Id: 1,
	Name: "bask"
}, {
	Id: 2,
	Name: "voll"
}, {
	Id: 3,
	Name: "badminton"
}];

var reduceObj = arr.reduce(function(result, currentElement) {
   result[currentElement.Id] = currentElement.Name;
   return result;
}, {});

console.log(reduceObj);

Using Array.map() :

var arr = [{
	Id: 1,
	Name: "bask"
}, {
	Id: 2,
	Name: "voll"
}, {
	Id: 3,
	Name: "badminton"
}];

var mapObject = {}

arr.map(obj => {
  mapObject[obj.Id] = obj.Name
})

console.log(mapObject);

Upvotes: 0

Arvind Rachuri
Arvind Rachuri

Reputation: 128

You can check out the reduce() function!

let array = [
    {Id: 1, Name: "bask"},
    {Id: 2, Name: "voll"},
    {Id: 3, Name: "badminton"} 
];
console.log(_.reduce(array, function(result, obj){
    result[obj.Id] = obj.Name;
  return result;
}, {}));

You can checkout lodash an awesome library with many other such utilities!

Upvotes: 1

Robin
Robin

Reputation: 5427

You can do it in different ways, here one of them.

let dataArray = [
  {id: 1, name: 'bask'},
  {id: 2, name: 'voll'},
  {id: 3, name: 'badminton'}
]

let ouputObject = {}

dataArray.map(data => {
  ouputObject[`${data.id}`] = data.name
})

console.log(ouputObject)

outputObject will be

Object {
  1: "bask",
  2: "voll",
  3: "badminton"
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386540

You could take Object.fromEntries with the maped key/value pairs.

var array = [{ Id: 1, Name: "bask" }, { Id: 2, Name: "voll" }, { Id: 3, Name: "badminton" }],
    object = Object.fromEntries(array.map(({ Id, Name }) => [Id, Name]));

console.log(object);

Upvotes: 2

Code-Apprentice
Code-Apprentice

Reputation: 83517

You can do this with reduce():

var a = [
  {Id: 1, Name: "bask"},
  {Id: 2, Name: "voll"},
  {Id: 3, Name: "badminton"}
]

b = a.reduce((acc, item) => {
  acc[item.Id] = item.Name;
  return acc;
}
console.log(b);

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can use reduce to loop through array and build a object of desired key/value pair

let data = [{Id: 1, Name: "bask"},{Id: 2, Name: "voll"},{Id: 3, Name: "badminton"}]

let output = data.reduce((op, {Id, Name}) => {
  op[Id] = Name
  return op
},{})

console.log(output)

Upvotes: 2

Related Questions