通过匹配子对象值过滤数组对象

Filtering the Array Object by Matching SubObject values

我有一个对象数组:

sampledata = [{
    "id": 1,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 1"
    },
    "energy": -145.9,
    "pv": 83.72
}, {
    "id2": 2,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 2"
    },  
    "energy": -145.9,
    "pv": 83.72
}];

如果对象的 parameter 值与给定输入匹配,我想获取该对象的某些属性。

我试过:

let x={Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}
return this.sampledata.filter(data=> data['parameter']===x) 

基于匹配的parameter对象我想从数组对象中得到returnenergypv属性。 结果:

{
 "energy": -145.9,
  "pv": 83.72
}

谁能建议我如何过滤我的数据?

使用Array#every to iterate the keys of x, and check if all x values equal the same values of parameter. After filtering the object, map数组的对象到要求的格式:

const data = [{"id":1,"parameter":{"Num_Of_Floors":"2","East":"10","Window_Type":"Window Type 1"},"energy":-145.9,"pv":83.72},{"id2":2,"parameter":{"Num_Of_Floors":"2","East":"10","Window_Type":"Window Type 2"},"energy":-145.9,"pv":83.72}];

const x = {Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"};

const result = data.filter(({ parameter }) =>       
  Object.keys(x).every((key) => x[key] === parameter[key]))
  .map(({ energy, pv }) => ({ energy, pv }));
  
console.log(result);

在过滤方法中,使用array#every比较sampedatax的每个值,然后使用array#map得到pvenergy

const sampledata = [{ "id": 1, "parameter": { "Num_Of_Floors":"2", "East":"10", "Window_Type":"Window Type 1" }, "energy": -145.9, "pv": 83.72 }, { "id2": 2, "parameter": { "Num_Of_Floors":"2", "East":"10", "Window_Type":"Window Type 2" }, "energy": -145.9, "pv": 83.72
}];

let x= { Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}

var result = sampledata
              .filter(obj => Object
                .keys(obj.parameter)
                .every(k => obj.parameter[k] === x[k]))
              .map(({energy,pv}) => ({energy,pv}));
              
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }