javascript - Bygg Json från en array av objekt
Jag försöker använda TypeScript för att bygga ett JSON-objekt från en lista av objekt som detta:[
[
{ attribute: 'a', modifier: 121 },
{ attribute: 'b', modifier: 67 },
{ attribute: 'c', modifier: 121 },
{ attribute: 'd', modifier: 67 }
]
Jag skulle vilja få något som:
{
a: 121,
b: 67,
c: 121,
d: 67
}
Men jag kan helt enkelt inte få kläm på högre ordningens funktioner för att få det att fungera.
Svar #1
Du kan använda reduce-metoden som accepterar som parameter en callback-funktion.
Läs mer om reduce-metoden här.
let array=[
{ attribute: 'a', modifier: 121 },
{ attribute: 'b', modifier: 67 },
{ attribute: 'c', modifier: 121 },
{ attribute: 'd', modifier: 67 }
];
let obj=array.reduce(function(obj,item){
obj[item.attribute] = item.modifier;
return obj;
},{});
console.log(obj);Svar #2
Du kan använda Object.assign i kombination med Array#map.
var array = [{ attribute: 'a', modifier: 121 }, { attribute: 'b', modifier: 67 }, { attribute: 'c', modifier: 121 }, { attribute: 'd', modifier: 67 }],
result = Object.assign(...array.map(o => ({ [o.attribute]: o.modifier })));
console.log(result);Med destrukturerande tilldelning
var array = [{ attribute: 'a', modifier: 121 }, { attribute: 'b', modifier: 67 }, { attribute: 'c', modifier: 121 }, { attribute: 'd', modifier: 67 }],
result = Object.assign(...array.map(({ attribute, modifier }) => ({ [attribute]: modifier })));
console.log(result);