简体   繁体   中英

How to filter an array of objects by property?

Given the following array, which contains arrays of objects:

[
  [
    {color: blue, size: 3},
    {color: red, size: 1},
    {color: blue, size: 4}
  ],
  [
    {color: blue, size: 4},
    {color: green, size: 9},
    {color: gren, size: 3}
  ]
]

How could I filter the data so that I am only left with objects which have a proprty of blue, like this:

[
  [
    {color: blue, size: 3},
    {color: blue, size: 4}
  ],
  [
    {color: blue, size: 4}
  ]
]

It is in the context of D3js, but this maybe just a plain JavaScript question.

Here's one way:

outputArray = inputArray.map(function(a) {
                return a.filter(function(el) { return el.color === "blue"; });
              });

The .map() method creates a new array whose elements will be the result of calling the function you provide for each element in the original array. (If you want to overwrite the original array, just assign the result back to the same variable instead of to a new one.)

The .filter() method creates a new array with just the elements from the original which pass the test in the function you pass it.

Further reading:

您可以使用if-else语句遍历数组来循环遍历蓝色。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM