我有一个用于json数组的非常简单的代码片段,以及一个现在返回单个参数的javascript函数:

<!DOCTYPE html>
<html>
<body>

<h2>JSON Array Test</h2>

<p id="outputid"></p>

<script>
var arrayinput = '{"collection":[' +
'{"firstAttr":"XXXA","secAttr":"13156161","lastAttr":"01" },' +
'{"firstAttr":"XXXB","secAttr":"11153325","lastAttr":"02"  },' +
'{"firstAttr":"XXXC","secAttr":"14431513","lastAttr":"03"  },' +
'{"firstAttr":"XXXC","secAttr":"161714","lastAttr":"01"  },' +
'{"firstAttr":"XXXC","secAttr":"151415","lastAttr":"02"  },' +
'{"firstAttr":"XXXC","secAttr":"114516","lastAttr":"02"  },' +
'{"firstAttr":"XXXC","secAttr":"131417","lastAttr":"03"  },' +
'{"firstAttr":"XXXC","secAttr":"1311865","lastAttr":"03"  },' +
'{"firstAttr":"XXXC","secAttr":"1314153","lastAttr":"01"  },' +
'{"firstAttr":"XXXC","secAttr":"13312163","lastAttr":"01"  }]}';

obj = JSON.parse(arrayinput);
document.getElementById("outputid").innerHTML =
obj.collection[1].firstAttr + " " + obj.collection[1].secAttr;
</script>

</body>
</html>


现在的问题是,我不想只返回一个值,而是多个值。例如,应返回所有带有lastAttr=01的条目。

因此,我需要以下方面的帮助:

for(var i in obj) {
    if(lastAttr[i]="01") {
        document.getElementById("outputid").innerHTML =
        obj.collection[i].firstAttr + " " + obj.collection[i].secAttr;
    } else {

    }
}


对如何进行这项工作有任何想法吗?

最佳答案

如果要执行需要使用Array.prototype.filter的位置:

var filteredArr = arr.collection.filter(function(item) {
   return item.lastAttr == "01";
});


最后,您可以使用Array.prototype.forEach迭代结果并执行一些操作:

var outputElement = document.getElementById("outputid");
filteredArr.forEach(function(item) {
    // Check that I used insertAdyacentHtml to be sure that all items
    // will be in the UI!
  outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});


另外,您可以流利地做到这一点:



var arr = {
  collection: [{
    firstAttr: "hello",
    secAttr: "world",
    lastAttr: "01"
  }, {
    firstAttr: "hello 2",
    secAttr: "world 2",
    lastAttr: "01"
  }]
};

var outputElement = document.getElementById("outputid");
var filteredArr = arr.collection.filter(function(item) {
  return item.lastAttr == "01";
}).forEach(function(item) {
  outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});

<div id="outputid"></div>

关于javascript - 使用JavaScript解析JSON数组返回选择的部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31677920/

10-11 12:07