0

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"}
1
  • 2
    I suggest using reduce(). Commented Jul 18, 2019 at 17:15

6 Answers 6

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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!

Comments

0

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

Comments

0

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"
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.