JS 遍历数组对象,求满足多个条件的相同属性的对象之和 (谢谢)
{
source: "HTML",
target: "JAVASCRIPT",
value: 11
},
{
source: "HTML",
target: "CSS",
value: 22
},
{
source: "HTML",
target: "JAVA",
value: 33
},
{
source: "HTML",
target: "JAVASCRIPT",
value: 44
}
];
又这样一组数组对象,我想通过遍历得到一个新的数组对象。同时满足 Source 相同和Target 相同的 value 进行求和。
希望得到的新数组对象如下。
console.log(result)
result = [
{
source: "HTML",
target: "JAVASCRIPT",
value: 55
},
{
source: "HTML",
target: "CSS",
value: 22
},
{
source: "HTML",
target: "JAVA",
value: 33
},
];
谢谢。 展开
按照你的要求,求满足多个条件的相同属性的对象之和的Javascript程序如下
<script type=text/javascript>
var obj = [{source: "HTML",target: "JAVASCRIPT",value: 11},
{source: "HTML",target: "CSS",value: 22},
{source: "HTML",target: "JAVA",value: 33},
{source: "HTML",target: "JAVASCRIPT",value: 44}];
var result=[];
var flag=true;
result.push(obj[0]);
for(var i=1;i<obj.length;i++){
flag=true;
for(var j=0;j<result.length;j++){
if(obj[i].source==result[j].source && obj[i].target==result[j].target){
flag=false;
result[j].value=obj[i].value+result[j].value;
}
}
if(flag==true)
result.push(obj[i]);
}
document.write(JSON.stringify(result));
</script>
源代码