[英]Convert array to object, based on even/odd index
I am trying to convert an array to an object based on whether the index of array is odd or even. 我试图根据数组的索引是奇数还是偶数将数组转换为对象。
For example,, 例如,,
Input: ["name", "Tom", "age", 20]
输入:
["name", "Tom", "age", 20]
output: { "name": "tom","age": 20 }
输出:
{ "name": "tom","age": 20 }
It can be implemented using basic functions of JavaScript such as forEach
, map
, and filter
. 它可以使用JavaScript的基本功能实现,例如
forEach
, map
和filter
。 But I want more simple code. 但我想要更简单的代码。
So I checked docs of underscore.js, but I couldn't find a good way. 所以我检查了underscore.js的文档,但我找不到一个好方法。 Is there any way to solve this simply?
有什么方法可以解决这个问题吗?
Interesting question, my two cents: 有趣的问题,我的两分钱:
Simple and performant for loop: 简单且高性能的循环:
const simpleArray = ["name", "Tom", "age", 20];
// Modifying the Array object
Array.prototype.toObject = function() {
let r = {};
for(let i = 0; i < this.length; i += 2) {
let key = this[i], value = this[i + 1];
r[key] = value;
}
return r;
}
// Or as a function
const toObject = arr => {
let r = {};
for(let i = 0; i < arr.length; i += 2) {
let key = arr[i], value = arr[i + 1];
r[key] = value;
}
return r;
}
const simpleObjectOne = simpleArray.toObject(); // First method
const simpleObjectTwo = toObject(simpleArray); // Second method
You could use Array#forEach
and a check for the index, if uneven, then assign the element to the key from the last item. 您可以使用
Array#forEach
并检查索引(如果不均匀),然后将元素分配给最后一项的键。
var array = ["name", "Tom", "age", 20], object = {}; array.forEach(function (a, i, aa) { if (i & 1) { object[aa[i - 1]] = a; } }); console.log(object);
The same with Array#reduce
与
Array#reduce
相同
var array = ["name", "Tom", "age", 20], object = array.reduce(function (r, a, i, aa) { if (i & 1) { r[aa[i - 1]] = a; } return r; }, {}); console.log(object);
var input = ["name", "Tom", "age", 20] ;
var output = {}
input.forEach((x, i, arr) => {
if (i % 2 === 0) output[x] = arr[i+1];
});
console.log(output); //{ name: 'Tom', age: 20 }
You may also use reduce 您也可以使用reduce
var arr = ["name", "Tom", "age", 20], obj = arr.reduce((p,c,i,a) => (i%2 ? p[a[i-1]] = c : p[c],p),{}); console.log(obj);
for this operation as follows; 对于此操作如下;
Underscore solution: 下划线解决方案:
output = _.object(..._.partition(input, (_, i) => !(i % 2)))
_.partition
will partition the array into [['name', 'age'], ["tom", "20"]]
. _.partition
将数组分为[['name', 'age'], ["tom", "20"]]
。 In other words, it returns an array containing two subarrays--in this case, one array of keys and one array of values. 换句话说,它返回一个包含两个子数组的数组 - 在本例中,是一个键数组和一个值数组。
_.object
takes an array of keys and an array of values as parameters, so we use ...
to pass the subarrays in the value returned by _.partition
to it as two parameters. _.object
将一组键和一个值数组作为参数,因此我们使用...
将_.partition
返回的值中的子_.partition
作为两个参数_.partition
给它。
If you're into very functional, semantic code: 如果您使用非常实用的语义代码:
const even = i => !(i % 2);
const index = fn => (_, i) => fn(i);
output = _.object(..._.partition(input, index(even)))
Recursive solution: 递归解决方案:
function arrayToObject([prop, value, ...rest], result = {}) {
return prop ? arrayToObject(rest, Object.assign(result, {[prop]: value})) : result;
}
Iterative solution: 迭代解决方案:
function arrayToObject(arr) {
const result = {};
while (arr.length) result[arr.shift()] = arr.shift();
return result;
}
A simple for loop 一个简单的for循环
var arr = ["name", "Tom", "age", 20, "address"];
var obj = {};
for (var i = 0; i < arr.length; i+=2){
//First iteration: assign obj["name"] to "Tom"
//Second iteration: assign obj["age"] to 20
//Third iteration: assign obj["address"] to "" because arr[5] does not exist
obj[arr[i]] = arr[i+1] || "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.