如何从json对象返回一系列键?

时间:2017-07-09 22:04:47

标签: json javascript-objects

我从JsonPlaceholder API

以下列方式构建了json数据
'1': {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat",
  "body": "quia et suscipit\nsuscipit" 
}

我将id映射为对象的键,现在想要返回说出的对象' 1'通过' 10'来自上面显示的修改后的HTTP响应。

我尝试使用lodash _.pick()

_pick(object, ['1', '10']);

但只返回对象' 1'和' 10'而不是' 1'通过' 10'

感谢所有帮助。

2 个答案:

答案 0 :(得分:0)

您是否考虑过将它们放入数组中然后对其进行过滤?

let data = [
  { id: 1 }, { id: 2 }, { id: 11 }
];

let filtered = data.filter(e => { return e.id >= 1 && e.id <= 10 });

console.dir(data);
console.dir(filtered);

如果你不能并且在JSON对象中坚持使用它们,可能会首先提取值:

let json = {
  '1': {
       "userId": 1,
       "id": 1,
       "title": "sunt aut facere repellat",
        "body": "quia et suscipit\nsuscipit" 
      },
  '10': {
       "userId": 10,
       "id": 10,
       "title": "sunt aut facere repellat",
        "body": "quia et suscipit\nsuscipit" 
      },
  '11': {
       "userId": 11,
       "id": 11,
       "title": "sunt aut facere repellat",
        "body": "quia et suscipit\nsuscipit" 
      }
};

var filtered = 
  Object
    .keys(json).map(key => json[key])
    .filter(val => val.id >= 1 && val.id <= 10);

console.dir(json);
console.dir(filtered);

答案 1 :(得分:0)

由于你已经在使用lodash,为什么不只是使用range来创建一个整数数组,然后映射它也将它们转换为字符串。

_.pick(object, _.range(1,10).map(_.toString));