Filter object object in javascript (filter or reduce?)

What is the best practice for filtering or reducing an object? I would do it through a for-loop and create a new array, but understand that you can do it somehow through the filter property in JavaScript?

var myObject = [
  {dimensions: [451, 255], margins: [0, 2, 0, 29]}, 
  {dimensions: [222, 390], margins: [0, 5, 0, 37]},
  {dimensions: [333, 390], margins: [0, 8, 0, 37]}
];

I would like to separately separate the sizes, properties and fields of the second and fourth properties in the array:

var dimension = [ 451, 222, 333 ];
var margins = [ 2, 29, 5, 37, 8, 37 ];

Also, if I filter an object and update these variables, is there a way to map them? Or I should have it as shown below, after which:

var dimension = [ a: 451, b: 222, c: 333];
var margins = [ a: [2, 29], b : [5, 37], c: [8, 37] ];
+4
source share
2 answers

You can use reduce:

var myObject = [{
  dimensions: [451, 255],
  margins: [0, 2, 0, 29]
}, {
  dimensions: [222, 390],
  margins: [0, 5, 0, 37]
}, {
  dimensions: [333, 390],
  margins: [0, 8, 0, 37]
}];


var results = myObject.reduce(function(acc, item) {
  acc.dimensions.push(item.dimensions[0]);
  acc.margins.push(item.margins[1], item.margins[3]);
  return acc;
}, { dimensions: [], margins: [] });

console.log(results); // {dimensions: Array[3], margins: Array[6]}

Working script: https://jsfiddle.net/9ynez03c/

myObject:

var dimensions = results.dimensions;
var margins = results.margins;

var updateMyObject = function() {
  myObject.forEach(function(item, i) {
    item.dimensions[0] = dimensions[i];
    item.margins[1] = margins[i * 2];
    item.margins[3] = margins[i * 2 + 1];
  })
};
updateMyObject();

. , , - , , / , .

: https://jsfiddle.net/adrice727/g01s80qf/

+4

, , (, , 5, ). .

var myObject = [
  {dimensions: [451, 255], margins: [0, 2, 0, 29]}, 
  {dimensions: [222, 390], margins: [0, 5, 0, 37]},
  {dimensions: [333, 390], margins: [0, 8, 0, 37]}
]

var dimensions = [];
var margins = [];

myObject.forEach(function(item) {
  dimensions.push(item.dimensions[0]);
  margins.push(item.margins[1]);
  margins.push(item.margins[3]);

  // or by using concat():
  // dimensions = dimensions.push(item.dimensions[0]);
  // margins = margins.concat([item.margins[1], item.margins[3]]);
});

console.log("dimensions:", dimensions);
console.log("margins:", margins);
Hide result
0

Source: https://habr.com/ru/post/1667465/


All Articles