Reputation: 1968
i want to retreive the properties x,y,z from the data structure below and store it in a seperate array.
below is the data structure as logged in console
object_arr [{…}]0:
first_property: "color"
id: 25
x: 10
y: 50
z: 56
_proto__: Objectlength: 1__proto__: Array(0)
I want to get the output as below,
final_output (3) {10, 50, 56}
i have tried using
const final_output = arr_obj.map(m => m.x);
this returns the x value properly however, when i try below,
const final_output = arr_obj.map(m => {m.x;
m.y;
m.z;});
This gives undefined value.
how do i retrieve all three x,y,z values from the above data structure arr_objects
.
Could someone help me fix this. thanks.
Thanks.
Upvotes: 0
Views: 70
Reputation: 5061
You can use reduce:
const final_output = arr_obj.reduce((prev, obj) => {
prev.push(Object.values(obj)); //Just add the values you want here
return prev;
}, []);
// [[10, 50, 56], ...]
Upvotes: 1
Reputation: 657
You can access the array of objects and then use individual properties.
For example var object_arr[0] -- will give object on the 0th index. And from this object, you can reference properties x, y and z (for example: object_arr[0].x, object_arr[0].y)
Since object_arr is an array you can loop thru it and fetch values.
var output = [];
for(var i = 0; i < object_arr.length; i++){
output.push(
{ 'x' : object_arr[i].x,
'y': object_arr[i].y,
'z': object_arr[i].z
});
}
Another way to do this is:
var output = [];
object_arr.forEach(function(item, index){
output.push(
{
'x' : item.x,
'y' : item.y,
'z' : item.z,
}
);
});
If you just want an array with those 3 values in it, that can be very straight forward (0 is the index you want to get values of):
var output = [object_arr[0].x, object_arr[0].y, object_arr[0].z];
If you just need one object and not an array then you can do following:
var output = { 'x' : object_arr[0].x, 'y': object_arr[0].y, 'z': object_arr[0].z };
Upvotes: 0
Reputation: 289
const final_output = arr_obj.map(m => {
return [
m.x,
m.y,
m.z
]
});
Upvotes: 1
Reputation: 550
you can use foreach and assign to temporary object
let newArray = []
arr_obj.forEach((element) => {
newArray.push({x: element.x,y: element.y,z: element.z})
})
Upvotes: 0