I have an array of objects as follow:
[
{
"card_key": "Edition",
"card_value": "Elite Fight Night"
},
{
"card_key": "Card ID",
"card_value": "15824885587"
}
]
and I want the output as follow:
{
"Edition":"Elite Fight Night",
"Card ID":"15824885587"
}
How can I do this in javaScript? I m beginner of js. Not know how can I do this
CodePudding user response:
Just iterate through the array and save the value of card_key
as key and card_value
as the value for your new object.
Something as shown below
obj_array = [
{
"card_key": "Edition",
"card_value": "Elite Fight Night"
},
{
"card_key": "Card ID",
"card_value": "15824885587"
}
]
objs1 = {}
for (const x of obj_array)
objs1[x["card_key"]] = x["card_value"]
console.log(objs1)
CodePudding user response:
You can use map
and Object.fromEntries
const data = [
{
"card_key": "Edition",
"card_value": "Elite Fight Night"
},
{
"card_key": "Card ID",
"card_value": "15824885587"
}
]
const result = Object.fromEntries(data.map(d => [d.card_key, d.card_value]))
console.log(result)
CodePudding user response:
let arr = [
{
"card_key": "Edition",
"card_value": "Elite Fight Night"
},
{
"card_key": "Card ID",
"card_value": "15824885587"
}
];
let finalObj = {};
for(let i = 0; i < arr.length; i ) {
let obj = arr[i];
finalObj[obj['card_key']] = obj['card_value'];
}
console.log(finalObj);
CodePudding user response:
If data has structure that you provided, you can use this code:
const input = [
{
"card_key": "Edition",
"card_value": "Elite Fight Night"
},
{
"card_key": "Card ID",
"card_value": "15824885587"
}
];
const expectedData = input.reduce((acc, item) => ({...acc, [item.card_key]: item.card_value}), {});
console.log(expectedData);
This is a bracket notation that allowing to use dynamic object keys.
Links:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
https://javascript.info/object
Reduce it is a function, that allows to calculate value based on input array. You can read about reduce here:
https://javascript.info/array-methods#reduce-reduceright
And also about spread operator (...):
https://javascript.info/rest-parameters-spread#spread-syntax
CodePudding user response:
const data = [{
"card_key": "Edition",
"card_value": "Elite Fight Night"
},
{
"card_key": "Card ID",
"card_value": "15824885587"
}
]
console.log(data.reduce((a, c) => {
a[c.card_key] = c.card_value;
return a
}, {}))