我有json数组值,它有年龄和数字。我想创建一个新的数组,其中包含{"num":2}
(即)需要返回[{"age":2,"num":2},{"age":3,"num":2}]
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val = {"num":1};
}
array_val.filter(fetchList)
console.log(array_val);

答案 0 :(得分:1)
您需要使用filter()
var fetched_object = array_val.filter(function(obj) {
return obj.num == 1;
});
注意:像@NinaScholz一样,你需要JSON.parse
字符串,所以它是一个数组。
答案 1 :(得分:1)
我在您的代码中看到了2个问题:
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val.num === 2; // return only records whose num is 2
}
// here you parse string into JSON and apply the filter
var data = JSON.parse(array_val).filter(fetchList);
console.log(data);

答案 2 :(得分:1)
你需要解析JSON字符串JSON.parse()
。匹配条件错误。num
是对象的内在属性。所以你需要匹配a.num == 2
。不要忘了添加==
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(a) {
return a.num == 2;
}
var res = JSON.parse(array_val).filter(fetchList)
console.log(res);

答案 3 :(得分:1)
这应该这样做
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
console.log(array_val);
function fetchList(array_val) {
return array_val.num == 2;
}
array_val = array_val.filter(fetchList)
console.log(array_val);
答案 4 :(得分:0)
这样可以改为:
var requiredValue = array_val.filter(function(item){return item.num === 2; });
答案 5 :(得分:0)
试试这个
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
var newarr =[]
for(let i of array_val){
if(i.num == 2){
newarr.push(i);
}
}
console.log(newarr);