如何在JavaScript中的单独数组中保存具有多个名称/值对的JSON字符串数组

时间:2016-07-16 13:21:30

标签: javascript json

我有以下JSON字符串。

[ { "id" : "1", "name" : "name1" },
{ "id" : "2", "name" : "name2" },
{ "id" : "3", "name" : "name3" },
{ "id" : "4", "name" : "name4" },
{ "id" : "5", "name" : "name5" } ]

如何将它保存在2个独立的“id&”name数组中,其中id和name数组与特定索引上的原始数组具有相同的数据。

4 个答案:

答案 0 :(得分:1)

var data = [ { "id" : "1", "name" : "name1" },
{ "id" : "2", "name" : "name2" },
{ "id" : "3", "name" : "name3" },
{ "id" : "4", "name" : "name4" },
{ "id" : "5", "name" : "name5" } ];

var ids = data.map(function(obj){
      return obj.id;
});

var names = data.map(function(obj){
      return obj.name;
});

使用地图功能

答案 1 :(得分:0)

这是一个通用处理,可以动态地处理n个元素。

var arr = [{
  "id": "1",
  "name": "name1"
}, {
  "id": "2",
  "name": "name2"
}, {
  "id": "3",
  "name": "name3"
}, {
  "id": "4",
  "name": "name4"
}, {
  "id": "5",
  "name": "name5"
}];
// key is an optional parameter.
// if key is sent only the array having that key is returned.
// else the entire structure is returned.
function processData(arr, key) {
    var obj = {},
      i,
      prop,
      len = arr.length;
    for (i = 0; i < len; i += 1) {
      elem = arr[i];
      for (prop in elem) {
        if (!obj[prop]) {
          obj[prop] = [];
        }
        obj[prop].push(elem[prop]);
      }
    }
    if (key) {
      return obj[key];
    }
    return obj;
  }
  // this logs the array containing "id" only.
console.log(processData(arr, "id"));
// this consoles the entire structure.
//console.log(processData(arr));

答案 2 :(得分:0)

我不完全理解您的问题,但此代码可能是确定目标的良好开端。

forEach功能可轻松实现此目的

var ids = [];
var names = [];
data.forEach(function(obj) {
 ids.push(obj.id);
 names.push(obj.name);
});

如果您也想使用map功能

var ids = data.map(function(obj){
  return obj.id;
});

var names = data.map(function(obj){
  return obj.name;
});

但如果您的目标是交叉兼容性。使用正常的for循环。

var ids = [];
var names = [];
for (var i in data) {
 ids.push(data[i].id);
 names.push(data[i].name);
}

输出

["1", "2", "3", "4", "5"] // ids

["name1", "name2", "name3", "name4", "name5"] // names

答案 3 :(得分:0)

&#13;
&#13;
var data = [ { "id" : "1", "name" : "name1" }, { "id" : "2", "name" : "name2" }, { "id" : "3", "name" : "name3" }, { "id" : "4", "name" : "name4" }, { "id" : "5", "name" : "name5" } ];

var result = {
  name: [],
  id: []
};
data.forEach(d => {
  result.name.push(d.name);
  result.id.push(d.id);
});
console.log(result);
&#13;
&#13;
&#13;