[英]Is it possible to return JSON key names based on value without knowing the key's name
Say I have the following JSON file: 说我有以下JSON文件:
{"attributes":
{
"blue":true,
"red":false,
"green":true,
"webAtt":
{
"webColor": "#EF5689",
"webSafe":true
}
}
}
but lets also say I do not know any JSON nodes except "attributes". 但是也可以说,除了“属性”外,我不知道任何JSON节点。 How would I go about finding which attributes are true?
我将如何查找哪些属性为真? Is this even possible?
这有可能吗? If not, must it be hardcoded for each child node of "attributes"?
如果不是,是否必须对“属性”的每个子节点进行硬编码?
I would like this done in JavaScript if possible. 如果可能,我希望在JavaScript中完成此操作。
EDIT: There is a reason why webAtt is there and its because I want to get "websafe" and not "webAtt" when sweeping. 编辑:有一个原因为什么webAtt在那里,因为我想在扫描时获取“ websafe”而不是“ webAtt”。
Object.keys()
returns the enumerable properties of the given object. Object.keys()
返回给定对象的可枚举属性。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
So you can do Object.keys(obj.attributes)
on the object above and it would return ["blue", "red", "green"]
. 因此,您可以对上面的对象执行
Object.keys(obj.attributes)
,它将返回["blue", "red", "green"]
。 You can then apply a filter to return only the attributes where the value in the object is true
. 然后,您可以应用过滤器以仅返回对象中值为
true
的属性。
var obj = { "attributes": { "blue":true, "red":false, "green":true } } console.log(Object.keys(obj.attributes).filter(function(attr) { return obj.attributes[attr] }))
You can do this with a for loop. 您可以使用for循环执行此操作。
var json = {"attributes": { "blue":true, "red":false, "green":true, "webAtt": { "webSafe":true, "webcolor":"#EF5689" } } }; for (var k in json.attributes) { if(json.attributes[k]==true){ console.log(k + ' ' + json.attributes[k]); } if(whatIsIt(json.attributes[k])=="Object"){ for(var l in json.attributes[k]){ if(json.attributes[k][l]==true){ console.log(l+' '+json.attributes[k][l]); } } } } //See credit below snippet var stringConstructor = "test".constructor; var arrayConstructor = [].constructor; var objectConstructor = {}.constructor; function whatIsIt(object) { if (object === null) { return "null"; } else if (object === undefined) { return "undefined"; } else if (object.constructor === stringConstructor) { return "String"; } else if (object.constructor === arrayConstructor) { return "Array"; } else if (object.constructor === objectConstructor) { return "Object"; } else { return "don't know"; } }
Credit for JSON object type Identifier code: How to check if JavaScript object is JSON JSON对象类型标识符代码: 如何检查JavaScript对象是否为JSON
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.