如何将输入json转换为node.js中的数组?

时间:2016-12-21 10:37:23

标签: javascript json node.js

在我的代码中,我有一个以json作为输入的函数:

[{
    "location": {},
    "_id": "5852d6fe29a15b4e6f9fc69d"
}, {
    "location": {},
    "_id": "5852d71529a15b4e6f9fc69e"
}, {
    "location": {},
    "_id": "5852d73229a15b4e6f9fc69f"
}, {
    "location": {},
    "_id": "5852d75b29a15b4e6f9fc6a0"
}]

我需要将其转换为结果为数组:

["5852d6fe29a15b4e6f9fc69d", "5852d6fe29a15b4e6f9fc69d",
 "5852d73229a15b4e6f9fc69f", "5852d75b29a15b4e6f9fc6a0"]

这个json是我函数的一个参数,基本上块代码如下所示:

function parseJson(inputJson) {   
    if (inputJson!= undefined) {
        var outputArray = 
    }
}

什么是解析数据的最佳方式?

3 个答案:

答案 0 :(得分:0)

以下是使用Array.prototype.map()的示例:

var json = [{"location": {}, "_id": "5852d6fe29a15b4e6f9fc69d"}, {"location": {}, "_id": "5852d71529a15b4e6f9fc69e"}, {"location": {}, "_id": "5852d73229a15b4e6f9fc69f"}, {"location": {}, "_id": "5852d75b29a15b4e6f9fc6a0"}],
    arr = json.map(item => item._id);

console.log(arr);

答案 1 :(得分:-1)

您可以使用Array.prototype.map

let myJSON = [
    { location: {}, _id: 5852d6fe29a15b4e6f9fc69d },
    { location: {}, _id: 5852d71529a15b4e6f9fc69e },
    { location: {}, _id: 5852d73229a15b4e6f9fc69f },
    { location: {}, _id: 5852d75b29a15b4e6f9fc6a0 }
];
let myArray = myJSON.map(obj => obj._id);

答案 2 :(得分:-1)

您可以使用map方法使用映射函数将数组转换为另一个数组:



var oldArray = [ { "location": {}, "_id": "5852d6fe29a15b4e6f9fc69d" },
  { "location": {}, "_id": "5852d71529a15b4e6f9fc69e" },
  { "location": {}, "_id": "5852d73229a15b4e6f9fc69f" },
  { "location": {}, "_id": "5852d75b29a15b4e6f9fc6a0" } ];


var newArray = oldArray.map(function(element){
  return element._id;
});//map()

console.log( newArray );