如何查找JSON对象是否包含数字并返回数字? [英] How to find if a JSON object contains numbers and return them?
问题描述
假设我有一个 json 对象的问题,这是动态地来自随机dataset
.我想搜索 json 的问题,然后执行一些操作操作该 json 对象的数字值有.我可以使用简单的for..of遍历Object
并获取整个键,但是我不确定如何遍历对象中的每个键值对并返回数字.下面给出一个示例:
Lets say I have a jsonobject and this is coming from a random dataset
dynamically. I would like to search through the jsonand do some manipulation on the number values of that jsonobject if there are any. I could loop through the Object
by using a simple for..of and get the whole key but I am not sure how to go through every key value pair in the object and return the numbers. The following gives an example:
var obj = {
"a0": {
"count": 41,
"name": "Park",
},
"a1": {
"count": 52,
"name": "Greg",
},
"a2": {
"count": 150,
"name": "Sylvain",
},
"a3": {
"count": 276,
"name": "Macho",
},
"a4": {
"count": 36,
"name": "Mariam",
},
"a5": {
"count": 39,
"name": "Blanca",
}
}
我可以如下遍历它:
for (let i of Object.keys(obj)) {
console.log(obj[i]);
}
除了hasOwnProperty
和keys
之外,我在Object
上找不到其他任何属性,这些属性实际上可以为我提供这些值.我可以通过执行obj[i].count
来简单地访问count的值,但是我不知道它是否具有count.我正在寻找一种获取值并检查其类型并将其作为数组返回或对数字值进行一些操作的通用方法.
I couldn't find any other properties on the Object
other than hasOwnProperty
and keys
which could actually give me the values. I could simply access the values of the count by doing obj[i].count
, but I wouldn't know if it has count. I am looking for a generic way to get the values and check for its type and return them as an array or do some manipulation with the number values.
我正在寻找提取对象中具有数字值的属性.
I am looking to extract the properties which have numeric values in the object.
有人可以帮助我吗?
谢谢.
推荐答案
使用 Array#map .在地图中使用 Array#reduce 仅获取具有数值的属性:
Use Object#keys, and iterate the array of keys with Array#map. In the map use Array#reduce to get just the properties that has numeric values:
创建数字数组:
const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};
const result = Object.keys(obj).map((key) => {
const o = obj[key];
return Object.keys(o).reduce((r, k) => typeof o[k] === 'number' ?
Object.assign(r, { [k]: o[k] }) : r , {});
});
console.log(result);
您可以使用 Object#entries (如果目标浏览器中支持它们,或者使用polyfill:
And you can shorten it a bit by using Object#values, and Object#entries if they are supported in the target browser, or by using a polyfill:
const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};
const result = Object.values(obj).map((o) =>
Object.entries(o).reduce((r, [k, v]) => typeof v === 'number' ?
Object.assign(r, { [k]: v }) : r , {})
);
console.log(result);
这篇关于如何查找JSON对象是否包含数字并返回数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!