0

I would like to know how to convert the input json array to a json object in the expected format using Javascript

Here is my input array

[
    {
    "Id": 1,
    "Name": "One"
    },
    {
    "Id": 2,
    "Name": "Two"
    },
    {
    "Id": 3,
    "Name": "Three"
    }
]

Expected json object output

{ "1" : "One",
  "2" :"Two",
  "3" :"Three"
}
brk
  • 48,835
  • 10
  • 56
  • 78
goldilocks
  • 31
  • 2
  • 7
  • What you seem to actually be wanting to know is how to convert an array of objects into a single object that uses the `id` as the property names/keys. – Herohtar May 09 '19 at 03:18
  • 1
    Possible duplicate of [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – Herohtar May 09 '19 at 03:18
  • 3
    Have you tried anything? In that case, please include it. Also, when you say `JSON`, you are implicitly saying that your input and expected output will be strings. Maybe you just want to know how to convert array of objects to a single object. – Shidersz May 09 '19 at 03:21
  • Please note that your `Id` entries are numbers in the first structure and become strings in your expected result... – arvymetal May 09 '19 at 03:24

4 Answers4

2

You can use array reduce and pass an empty object in the accumulator. Then inside the reduce callback update the accumulator array by adding key and value

let obj = [{
  "Id": 1,
  "Name": "One"
}, {
  "Id": 2,
  "Name": "Two"
}, {
  "Id": 3,
  "Name": "Three"
}]


let newObj = obj.reduce(function(acc, curr) {

  acc[curr.Id] = curr.Name;
  return acc;
}, {})


console.log(newObj)
brk
  • 48,835
  • 10
  • 56
  • 78
1

let arr = [{
    "Id": 1,
    "Name": "One"
  },
  {
    "Id": 2,
    "Name": "Two"
  },
  {
    "Id": 3,
    "Name": "Three"
  }
]

let json1 = {}

for (const s of arr) {
  json1[s.Id] = s.Name
}

console.log(json1)
mingchau
  • 450
  • 3
  • 12
0

You only need a simple for loop to iterate trough the array and then assign new properties to the resulting object, like so:

let array = [{ "Id": 1, "Name": "One"}, {"Id": 2, "Name": "Two"}, {"Id": 3, "Name": "Three"}];

let obj = {};

for (let i = 0; i < array.length; i++) {
    const elem = array[i];
    obj[elem.Id] = elem.Name;
}

console.log(obj);
Francisco Hanna
  • 1,137
  • 1
  • 11
  • 27
0

Iterate over the array of objects, use Object.values() to get the values for each object and then create new obects using the first value as the key.

var arr = [ { "Id": 1, "Name": "One" }, { "Id": 2, "Name": "Two" }, { "Id": 3, "Name": "Three" } ];

var jsonObj = {};


arr.forEach(function(item){
  var values = Object.values(item);
  jsonObj[values[0]] = values[1];

})

 console.log(jsonObj); // gives {"1": "One","2": "Two","3": "Three"}
 
gavgrif
  • 15,194
  • 2
  • 25
  • 27