过滤嵌套数组> =

时间:2020-05-12 16:01:36

标签: javascript arrays

我有一个像这样的数组:

const rawdata = [
  {
    top_feature_col: "s9",
    top_feature_row: 1,
    data: [{ cluster: 0, value: 151508, opportunity_perc: 69 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 0, value: 127518, opportunity_perc: 70 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 1, value: 12668, opportunity_perc: 40 }]
  }
];

我想过滤opportunity_perc >= 50的位置,但是我不知道该怎么做。

结果应为:

const result = [
  {
    top_feature_col: "s9",
    top_feature_row: 1,
    data: [{ cluster: 0, value: 151508, opportunity_perc: 69 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 0, value: 127518, opportunity_perc: 70 }]
  }
];

3 个答案:

答案 0 :(得分:7)

您应该尝试使用filter类的Array方法:

const result = rawdata
    .filter(({data}) => data[0].opportunity_perc >= 50);

如果data数组仅包含一个元素(按照您的示例),那么这将是有效的,如果不是,则应在请求中指定行为。

答案 1 :(得分:1)

const rawdata = [
    {
        top_feature_col: "s9",
        top_feature_row: 1,
        data: [{cluster: 0, value: 151508, opportunity_perc: 69}]
    },
    {
        top_feature_col: "s9",
        top_feature_row: 2,
        data: [{cluster: 0, value: 127518, opportunity_perc: 70}]
    },
    {
        top_feature_col: "s9",
        top_feature_row: 2,
        data: [{cluster: 1, value: 12668, opportunity_perc: 40}]
    }
];

let filteredData = rawdata.filter((item) => {
    return ((item.data[0].opportunity_perc) >= 50);
});

console.log(filteredData);

答案 2 :(得分:1)

使用具有分解功能的filter方法,并使用opportunity_perc进行检查

const rawdata = [
  {
    top_feature_col: "s9",
    top_feature_row: 1,
    data: [{ cluster: 0, value: 151508, opportunity_perc: 69 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 0, value: 127518, opportunity_perc: 70 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 1, value: 12668, opportunity_perc: 40 }]
  }
];

const res = rawdata.filter(
  ({ data: [{ opportunity_perc }] }) => opportunity_perc >= 50
);

console.log(res);