如何从数组创建键值对

时间:2017-03-02 08:53:53

标签: javascript jquery hashmap hashtable

这是我的json:

[["123", "456", "789", "user1"],
 ["987", "654", "321", "user2"]]

我已经在我的代码中使用了这种方式:

var rows = [ 
  ["123","456","789","user1"] ,
  ["987","654","321","user2"]
];

我想将user1和user2作为键并保留为值。如何从这个json创建一个键值对?

2 个答案:

答案 0 :(得分:4)

使用Array#reduce方法生成对象。



var data = [
  ["123", "456", "789", "user1"],
  ["987", "654", "321", "user2"]
];

var res = data
  // iterate over the array elements
  .reduce(function(obj, arr) {
    // define the object property by popping the last element
    // if you dont want to update the origian array 
    // element then take copy of inner array using slice()
    obj[arr.pop()] = arr;
    // return the object reference
    return obj;
    // set initial value as an empty object
  }, {})

console.log(res);



 如果您不想更新原始数组:



var data = [
  ["123", "456", "789", "user1"],
  ["987", "654", "321", "user2"]
];

var res = data.reduce(function(obj, arr) {
  obj[arr[arr.length - 1]] = arr.slice(0, -1);
  return obj;
}, {})

console.log(res);




更新:如果同一用户有多个元素,则可以将它们合并。



var data = [
  ["123", "456", "789", "user1"],
  ["987", "654", "321", "user2"],
  ["abc", "def", "ghi", "user1"]
];

var res = data.reduce(function(obj, arr) {
  // initialize propety as an empty array if undefined
  obj[arr[arr.length - 1]] = obj[arr[arr.length - 1]] || [];
  // push the array values into the array
  [].push.apply(obj[arr[arr.length - 1]], arr.slice(0, -1));
  return obj;
}, {})

console.log(res);




答案 1 :(得分:0)

您可以使用Array.prototype.forEach()进行迭代,然后将弹出的项目推送到数组中。

var arr = {};
var rows = [ 
["123","456","789","user1"] ,
["987","654","321","user2"],
  ["12213","45216","78219","user1"],
  ["abc","def","ghi","user1"],
  ["uvw","wxy","xyz","user2"]
 ];
rows.forEach(function(item){  
  var val = item[item.length-1];
  if ( arr[val] ) {   
   arr[item.pop()].push(item);
  } else {
    arr[item.pop()] = [item];
  }
});
console.log(JSON.stringify(arr));

如果您希望将所有值分组并映射到密钥:

var arr = {};
var rows = [ 
["123","456","789","user1"] ,
["987","654","321","user2"],
  ["12213","45216","78219","user1"],
  ["abc","123","ghi","user1"],
  ["678","789","890","user2"]
 ];
rows.forEach(function(item){  
  var val = item[item.length-1];
  if ( arr[val] ) {
    arr[item.pop()] = arr[val].concat(item);
  } else {
    arr[item.pop()] = item;
  }
});
console.log(JSON.stringify(arr));