简体   繁体   English

如何从数组创建键值对

[英]how to create key value pair from an a array

This is my json : 这是我的json:

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

I have put it in this way in my code: 我已经在我的代码中这样写了:

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

I want user1 and user2 as key and remaining as values. 我希望将user1和user2作为键并保留为值。 How to create a key value pair from this json? 如何从这个JSON创建一个键值对?

Use Array#reduce method and generate the object. 使用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); 

If you don't want to update the original array : 如果您不想更新原始数组:

 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); 


UPDATE : If there is a chance for multiple elements for the same user, then you can combine them. 更新:如果同一用户有多个元素的机会,则可以将它们组合在一起。

 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); 

You can simply iterate using Array.prototype.forEach() and push the popped item into an array. 您可以简单地使用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)); 

If you want all the values grouped and mapped to the key : 如果要将所有值分组并映射到键:

 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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM