Skip to content Skip to sidebar Skip to footer

How To Retrieve Selective Properties From The Array Of Objects And Store As An Object Using Javascript?

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:

Solution 1:

const final_output = arr_obj.map(m => {
  return [
    m.x, 
    m.y,
    m.z
  ]
});

Solution 2:

You can use reduce:

const final_output = arr_obj.reduce((prev, obj) => {
  prev.push(Object.values(obj)); //Just add the values you want herereturn prev;
}, []);
// [[10, 50, 56], ...]

Solution 3:

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 };

Solution 4:

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})
})

Post a Comment for "How To Retrieve Selective Properties From The Array Of Objects And Store As An Object Using Javascript?"