Reputation: 1023
I have data as shown below:
0: Object { IG: "Low income", FLFPR: 47.00099945, lnGDP: 7.496679918, … }
1: Object { IG: "Upper middle income", FLFPR: 47.67599869, lnGDP: 9.302921813, … }
2: Object { IG: "Upper middle income", FLFPR: 15.18999958, lnGDP: 9.526954146, … }
3: Object { IG: "Lower middle income", FLFPR: 75.47899628, lnGDP: 8.802498179, … }
4: Object { IG: "High income", FLFPR: 47.82500076, lnGDP: 9.858328453, … }
5: Object { IG: "Upper middle income", FLFPR: 51.16600037, lnGDP: 9.011393414, … }
I need only say IG and FLFPR from each object. Also, I do not know the values IG and FLFPR. They are user inputs. For example, inputx = IG and inputy = FLFPR.
I tried using map but I couldn't get it to work. I know the below code is incorrect, but intutively this is what I need.
xydata = data.map(item => {x: item.inputx, y: item.inputy});
Is it right to use map in this context ?
dat = [{x: 8, y: 3, z:5},{x: 2, y: 10, z:5},{x: 11, y: 3, z:5},{x: 6, y: 6, z:5},{x: 5, y: 8, z:5}]
xText = 'x'
yText = 'y'
xydata = dat.map(item => ({x: item.[xText], y: item.[yText]}));
Upvotes: 0
Views: 36
Reputation: 11584
You can use []
to access object properties dynamically.
let x = {dog: 3, cat: 4, key: 5};
let key = 'dog';
console.log(x.key); // 5
console.log(x['key']); // also 5
console.log(x[key]); // 3
In your case:
xydata = data.map(item => ({x: item[inputx], y: item[inputy]}));
Similarly, you can use []
when creating objects with dynamic property names.
let key = 'dog';
let x = {
cat: 5,
[key]: 6,
key: 7,
};
console.log(x.key); // 7
console.log(x.dog); // 6
Upvotes: 1
Reputation: 37745
To access object values knowing key name is enough, You need to use proper key names to access values
change to this
xydata = data.map(item => ({x: item.IG, y: item.FLFPR}));
Upvotes: 1