通过匹配子对象值

时间:2017-11-16 19:14:56

标签: javascript jquery array-filter arrayobject

我有一个对象数组:

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对象,我想从数组对象返回energypv属性。 结果:

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

有人可以建议我如何过滤我的数据吗?

2 个答案:

答案 0 :(得分:0)

使用Array#every来迭代x的{​​{3}},并检查所有x值是否等于parameter的相同值。过滤对象后,keys数组的对象为所需格式:



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




答案 1 :(得分:0)

在过滤方法中,使用array#every比较sampedatax的每个值,然后使用array#map获取pv和{{1} }

energy
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);