Home > Enterprise >  Make arr of objects with the same key javascript
Make arr of objects with the same key javascript

Time:04-11

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!!

CodePudding user response:

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!

CodePudding user response:

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 using Object.entries()
  • Now, de-structure the [key, value] iterator to directly access prop x
  • Transform it to an object with x as the value

CodePudding user response:

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 );

  • Related