TrickOrTreat
TrickOrTreat

Reputation: 911

Key, Value mapping in Object Literals

I tripped over a javascript question

Initially, response from HTTP was like [...{67,90},{23,40}], Now in order to view this detail in pie chart, i had to convert it into [{x:67, y: 90}, {x:23, y:40}], but now i want this pie data to again look like [{67,90},{23,40}].

For Example:

g = [{x: 67, y:90}, {x: 23, y:40}]

I tried few things like : 1.

Object.keys(pieData).map((item) => {
            return {
                item.x, item.y
            }
        })

2.

Object.key(Object.entries(g))

Required result is:

g=[{67,90}, {23,40}]

Any help would be appreciated.

Second part of the above question is '67', '23' are actually indexes. Can we convert one of the values in index number of the array....?

Upvotes: 0

Views: 1038

Answers (3)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

Notice that the result g = [{67, 90}, {23, 40}] that you want is not valid javascript

  • I think that what you want is an array of objects [{67: 90}, {23: 40}] with the x as key and the y as value

To get that, as you post in your question you can use Array.prototype.map()

Code:

const g = [{x: 67, y:90}, {x: 23, y:40}];
const result = g.map(o => ({ [o.x]: o.y }));

console.log(result);

Upvotes: 1

Jamiec
Jamiec

Reputation: 136074

If you want the x as the key and the y as the value this is what you're looking for.

var g = [{x: 67, y:90}, {x: 23, y:40}];
var result = g.map(item => ({[item.x]:item.y}));
console.log(result);

Upvotes: 2

Maheer Ali
Maheer Ali

Reputation: 36564

Your expected output is wrong because it contains object without key:value pairs. You should return array of arrays. Use map() and return an array containing both properties.

let g = [{x: 67, y:90}, {x: 23, y:40}]
let res = g.map(({x,y}) => [x,y]);
console.log(res)

Upvotes: 1

Related Questions