'Make arr of objects with the same key javascript
I have arr
let arr = [
{tags: {x: 2, y: 12}},
{type: {x: 23, y: 44}},
{order: {x: 5, y: 1200}},
]
and need (the same key, but value must come from current x)
let arr = [
{tags: 2},
{type: 23},
{order: 5}
]
what I try
arr.map(({ k, v }) => { [k]: v.x });
Please about help!!
Solution 1:[1]
let arr = [
{tags: {x: 2, y: 12}},
{type: {x: 23, y: 44}},
{order: {x: 5, y: 1200}},
]
arr.map((item) => {
const newItem = {}
newItem[ Object.keys(item)[0]] = item[Object.keys(item)[0]].x
return newItem
})
This is my solution. It's worked but I don't think it is good answer!
Solution 2:[2]
This should be one possible way to obtain the desired objective.
Code Snippet
let arr = [
{tags: {x: 2, y: 12}},
{type: {x: 23, y: 44}},
{order: {x: 5, y: 1200}},
];
const res = arr.flatMap(
obj => Object.entries(obj).map(
([k, {x}]) => ({ [k]: x })
)
);
console.log(res);
Explanation
- Iterate over the array using
.flatMap()(to avoid nested-array in the result) - Take each object (
obj) and iterate over key-value pairs usingObject.entries() - Now, de-structure the
[key, value]iterator to directly access propx - Transform it to an object with
xas the value
Solution 3:[3]
You're moving in the right direction. You just need Object.entries to help you get k and v as an array [k, v].
let arr = [ {tags: {x: 2, y: 12}}, {type: {x: 23, y: 44}}, {order: {x: 5, y: 1200}} ];
const output = arr.flatMap(
o => Object.entries(o).map(([k,v]) => ({[k]:v.x}))
);
console.log( output );
Alternatively, since v has the same properties in all the elements, you can use destructuring as in the demo below:
let arr = [ {tags: {x: 2, y: 12}}, {type: {x: 23, y: 44}}, {order: {x: 5, y: 1200}} ];
const output = arr.flatMap(
o => Object.entries(o).map(([k,{x,y}]) => ({[k]:x}))
);
console.log( output );
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 | Takashi Anji |
| Solution 2 | |
| Solution 3 |
