'How can I get key values and correspond it to each other in js?
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
Solution 1:[1]
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)
Solution 2:[2]
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)
Solution 3:[3]
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);
Solution 4:[4]
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
Solution 5:[5]
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
}, {}))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Art |
| Solution 2 | R4ncid |
| Solution 3 | Ice Box |
| Solution 4 | |
| Solution 5 | a2441918 |
