如何查找JSON对象是否包含数字并返回它们?

时间:2017-11-16 19:51:03

标签: javascript json

假设我有一个对象,它来自一个随机dataset动态。我想搜索并对该对象的数值进行一些操作(如果有的话)。我可以通过使用简单的for..of循环遍历Object并获取整个密钥,但我不确定如何遍历对象中的每个键值对并返回数字。以下是一个例子:

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]);
}

除了ObjecthasOwnProperty之外,我无法在keys上找到任何其他属性,这些属性实际上可以为我提供值。我可以通过obj[i].count简单地访问计数值,但我不知道它是否有计数。我正在寻找一种通用的方法来获取值并检查它的类型并将它们作为数组返回或使用数值进行一些操作。

编辑:我希望提取对象中具有数值的属性。

任何人都可以帮助我。

谢谢。

2 个答案:

答案 0 :(得分:4)

使用Object#keys,并使用Array#map迭代密钥数组。在地图中使用Array#reduce来获取具有数值的属性:

创建一个数字数组:

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#valuesObject#entries,或者使用填充,则可以缩短它:

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);

答案 1 :(得分:0)

const 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"}};

var newArray = [];
for (var key in obj) {
newArray.push(obj[key].count)
}
console.log(newArray);