我有一个看起来像
的JSON对象{
"1F54716": [],
"1258820b-guid": [
{
"value": "true",
"property": "",
"say": "Hello",
},
{
"value": "false",
"property": "",
"say": "Hello",
}
],
}
有没有办法可以通过"值":" true"来过滤这个,所以只有值,其中value = true,然后我想要一个say =的计数你好 。非常感谢您的帮助,javascript世界的新手
答案 0 :(得分:2)
var theObject = {"1F54716": [], "1258820b-guid": [
{"value": "true", "property": "", "say": "Hello"},
{"value": "false", "property": "", "say": "Hello"},
{"value": "true", "property": "", "say": "Bye"},
{"value": "true", "property": "", "say": "Hello"}
]}; // Array has 3 value "true" objects and 2 of them count as say "Hello".
function extractArrayWithValueAndSay(obj) {
for (var k in obj) {
if (obj[k] && obj[k].length && "value" in obj[k][0] && "say" in obj[k][0]) {
return obj[k];
}
}
return [];
}
var sourceArray = extractArrayWithValueAndSay(theObject);
var filteredValueTrueArray = sourceArray.filter(function (obj) {
return obj && obj.value == "true";
});
var filteredSayHelloCount = filteredValueTrueArray.filter(function (obj) {
return obj && obj.say == "Hello";
}).length;
答案 1 :(得分:0)
答案 2 :(得分:0)
类似的东西:
function filterObj(obj) {
let res = {};
let res.count = 0;
// iterate through all keys in the object
Object.keys(obj).forEach( k => {
// if this sub-object has
res[k] = obj[k].filter(o => {
// if say = hello increment our counter by 1. Otherwise it stays the same
res.count += o.say === 'hello' ? 1 : 0;
// if the object has value === true, keep it in our final results
return o.value === "true";
});
);
// res.count is the number of say === 'hello'
// and res contains only objects with value === 'true'
return res;
}
应该有效。另一个解决方案是JSON解析对象,并使用o.value作为测试来保留它,这取决于你是否计划继续在JS中处理这个对象或者接下来将它序列化。
答案 3 :(得分:0)
我建议使用Underscore.js框架。它提供了多种方法将数据搜索到javascript数组中。
var obj = {
"1F54716": [],
"1258820b-guid": [
{
"value": "true",
"property": "",
"say": "Hello",
},
{
"value": "false",
"property": "",
"say": "Hello",
}
],
}
var result = _.where(obj["1258820b-guid"], { value : "true"});
这里是Official website Underscorejs,可以继续阅读。