如何从json对象创建数组?

时间:2017-02-25 10:20:44

标签: json lodash

我的json看起来像这样,它由对象和一些其他属性组成:

let jsonobject =  {
       "one":{ id:'Peter'},
       "two":{ id:'John'},
       "three":{ id:'Ko'},
       "id":1,
       "name":'Jack'
}

我想将此转换为带有lodash或其他内容的数组,结果将是:

[{ id:'Peter'},
{ id:'John'},
{ id:'Ko'}]

所以我可以使用_.values(jsonobject)但是我怎么能抛弃那些显然没有对象的id和name属性?我想要一个紧凑的解决方案和/或使用lodash。

3 个答案:

答案 0 :(得分:3)

(1)获取外部对象的所有值,(2)过滤非对象项。

_.filter(_.values(jsonobject), _.isObject)

或者链式变体:

_(jsonobject).values().filter(_.isObject).value()

答案 1 :(得分:1)

您只需将filterisObject谓词一起使用即可获取值。

var result = _.filter(jsonobject, _.isObject);



let jsonobject = {
  "one": {
    id: 'Peter'
  },
  "two": {
    id: 'John'
  },
  "three": {
    id: 'Ko'
  },
  "id": 1,
  "name": 'Jack'
};

var result = _.filter(jsonobject, _.isObject);

console.log(result);

body > div { min-height: 100%; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以遍历对象中的键并将对象存储在数组中。

 var obj = {
       "one":{ id:'Peter'},
       "two":{ id:'John'},
       "three":{ id:'Ko'},
       "id":1,
       "name":'Jack'
};

var arr = [];
for(var key in obj){
    if(typeof obj[key] === 'object'){
        arr.push(obj[key]);
    }
}
console.log(arr);

相关问题