[英]How do I find a JSON value with a specific ID?
I have an object and I'm trying to find a specific value using an ID in ECMAScript6. 我有一个对象,正在尝试使用ECMAScript6中的ID查找特定值。
I've tried something like this: myvalue = this.json.find(x => x == '1234');
我已经尝试过这样的事情:
myvalue = this.json.find(x => x == '1234');
The JSON looks something like this: JSON看起来像这样:
{
"results": [
{
"abcde1234": {
"value": 4
}
},
{
"zxcv4567": {
"value": 2
}
}
]
}
All the examples I've found can only find off named key-value pairs. 我发现的所有示例只能找到命名的键值对。
const json = { '1234': { 'value' : 4}, '5678': { 'value' : 10} }; const value = json['1234']; console.log(value);
The JSON data doesn't seem proper. JSON数据似乎不正确。 But in case you are finding by key, you can directly access this, something like:
但是,如果您要查找密钥,则可以直接访问它,例如:
Parsed JSON maps directly to JavaScript types: Object, Array, boolean, string, number, null. 解析的JSON直接映射到JavaScript类型:对象,数组,布尔值,字符串,数字,空值。 Your example used
find()
which is (normally) a method used with arrays. 您的示例使用了
find()
(通常是数组使用的方法)。 If your JSON was structured like this, you could expect to use find: 如果您的JSON的结构如下,则可以使用find:
const jsonString = '["a", "b", "c"]';
const jsonData = JSON.parse(jsonString);
jsonData.find(x => x === "a"); // "a"
But it seems like your data is structured as an object, so you can use normal property access: 但是似乎您的数据是作为对象构造的,因此可以使用常规属性访问:
const jsonString = '{"1234": {"value": 4}, "5678": {"value": 10}}';
const jsonData = JSON.parse(jsonString);
jsonData["1234"] // {value: 4}
jsonData["1234"].value // 4
EDIT 编辑
OP changed the data example, so the above code is less directly applicable, but the general point is: once you parse it, it's just javascript . OP更改了数据示例,因此上面的代码不太直接适用,但是一般要点是:一旦解析了它, 它就是javascript 。
Try 尝试
json.results.find(x => /1234/.test(Object.keys(x)[0]));
json = { "results": [ { "abcde1234": { "value": 4 } }, { "zxcv4567": { "value": 2 } } ] } let r = json.results.find(x => /1234/.test(Object.keys(x)[0])); console.log(r);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.