Nishita Sinha
Nishita Sinha

Reputation: 45

Javascript Objects format conversion

How can i convert this:

{key: "A", value: {count:2}}
{key: "B", value: {count:5}}
{key: "C", value: {count:1}}

INTO THIS:

{key:"A", value: 2}
{key:"B", value: 5}
{key:"C", value: 1}

Upvotes: 0

Views: 38

Answers (3)

fedesc
fedesc

Reputation: 2610

Or for...of

const arr = [
  {key: "A", value: {count:2}},
  {key: "B", value: {count:5}},
  {key: "C", value: {count:1}}
];
for (let v of arr) v.value = v.value.count;
console.log(arr);

Though unlike map() this will mutate arr;

Upvotes: 1

Sascha A.
Sascha A.

Reputation: 4616

Use map for this.

let arr = [
  {key: "A", value: {count:2}},
  {key: "B", value: {count:5}},
  {key: "C", value: {count:1}}
];

let result = arr.map(obj => { return { key: obj.key, value: obj.value.count }});
console.log(result);

Upvotes: 1

hgb123
hgb123

Reputation: 14881

You could use map

const data = [
  { key: "A", value: { count: 2 } },
  { key: "B", value: { count: 5 } },
  { key: "C", value: { count: 1 } },
]

const res = data.map((obj) => ({
  key: obj.key,
  value: obj.value.count,
}))

console.log(res)

Upvotes: 1

Related Questions