Reputation: 414
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!!
Upvotes: 0
Views: 46
Reputation: 24638
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 );
Upvotes: 0
Reputation: 3691
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
.flatMap()
(to avoid nested-array in the result)obj
) and iterate over key-value pairs using Object.entries()
[key, value]
iterator to directly access prop x
x
as the valueUpvotes: 1
Reputation: 597
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!
Upvotes: 1