我有一个对象数组:
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
对象,我想从数组对象返回energy
和pv
属性。
结果:
{
"energy": -145.9,
"pv": 83.72
}
有人可以建议我如何过滤我的数据吗?
答案 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
比较sampedata
和x
的每个值,然后使用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);