Reputation: 1968
i want to retrieve certain properties from the array of object and store it in a array.
the data structure looks like below,
object_arr [{…}]0:
first_property: "color"
id: 25
x: 10
y: 50
z: 56
_proto__: Objectlength: 1__proto__: Array(0)
i want to retrieve x, y and z values so the output should be like below
(3) [10, 50, 56]
0: 10
1: 50
2: 56
length: 3
__proto__: Array(0)
so final_output[0] should give me 10, final_output[1] should give me 50 and final_output[2] should give 56
what i have tried?
let final_output = object_arr.map(m => {
return [
m.x,
m.y,
m.z
]
});
the final_output looks like this,
final_output [Array(3)]
0: (3) [10, 50, 56]
length: 1
the expected output is as below,
final_output (3) [10, 50, 56]
0: 10
1: 50
2: 56
length: 3
how can i fix this. could someone help me with this. thanks.
Upvotes: 0
Views: 54
Reputation: 50759
If your array only contains the one object, you can add its properties directly into an array like so:
const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];
const [{x, y, z}] = object_arr; // use destructuring to get the object keys from the array
const res = [x, y, z]; // create an array containing x, y, z properties
console.log(res);
If your array can contain multiple objects, you could use .flatMap()
by mapping your properties to an array, which will then fall into a larger resulting array. This way, all x
, y
and z
properties (of all objects) will be mapped to one larger output array:
const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];
const res = object_arr.flatMap(o => [o.x, o.y, o.z]);
console.log(res);
Upvotes: 0
Reputation: 50797
This is quite simple. I think your confusion is stemming from trying to work with the input array as a whole. If you only want the data from its first element, you don't need map
. Just address it directly with [0]
:
let object_arr = [{ first_property: "color", id: 25, x: 10, y: 50, z: 56}]
let final_output = [object_arr [0] .x, object_arr [0] .z, object_arr [0] .z];
console .log (final_output)
Upvotes: 1
Reputation: 3594
Do this:
let object_arr = { first_property: "color", id: 25, x: 10, y: 50, z: 56}
let final_output = [object_arr.x, object_arr.y, object_arr.z];
Upvotes: 1
Reputation: 175
You can clearly see :
final_output [Array(3)]
0: (3) [10, 50, 56]
which is array of array.
So to get value 10 you will have to do: final_output[0][0].
Or output=final_output[0];
Then output[0]
Upvotes: 0