我已经搜索过,没有任何匹配,所以在你提出修辞之前忘记复制粘贴的搜索。 :)
无论如何,在JavaScript(ES6)中,我有这个JSON
var myJson = {
'hello' : {x: 11, y:22},
'there' : {x:99, y:100}
};
我知道要删除JSON行,我只需要删除关键字 但我想删除的是基于属性条件,例如,我想删除X大于50的行,当然可以删除
delete myJson['there'].
但问题是,我无法事先知道哪个密钥符合标准,所以我不能使用删除。我也搜索并发现(不确定是否为真?)我无法遍历此JSON并获取循环索引,因此我可以将JSON行拼接出来,因为这不是数组而是对象。
基于排除X>的行的条件; 50,最终预期输出是:
myJson = {
'hello' : {x: 11, y:22}
};
谢谢!
答案 0 :(得分:0)
var myJson = {
'hello' : {x: 11, y:22},
'there' : {x:99, y:100}
};
for( i in myJson) {
if (myJson[i].x > 50) {
delete myJson[i];
}
}
答案 1 :(得分:0)
试试这个。 hasOwnProperty
检查的原因是确保密钥是对象的实际属性,并且不是来自原型。
var myObject = {
'hello' : {x: 11, y:22},
'there' : {x:99, y:100}
};
for(var prop in myObject) {
if(myObject.hasOwnProperty(prop)) {
if(myObject[prop].x > 50) {
delete myObject[prop];
}
}
}
console.log(myObject);

我将变量重命名为myObject
,因为它不是JSON。要从对象获取JSON,您将执行以下操作:
var myObject = {
'hello' : {x: 11, y:22},
'there' : {x:99, y:100}
};
var myJson = JSON.stringify(myObject);
console.log(myJson);