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"
}
4 Answers 4
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)
2 Comments
obj.reduce((r, v) => ({...r, [v.Id]: v.Name}), {}))obj.reduce((r,{Id, Name}) => ({...r, [Id]: Name}), {})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)
Comments
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);
Comments
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"}
idas the property names/keys.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.Identries are numbers in the first structure and become strings in your expected result...