简体   繁体   English

基于偶数/奇数索引将数组转换为对象

[英]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的基本功能实现,例如forEachmapfilter 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.

相关问题 如何根据奇数或偶数索引删除数组中的元素? - How to remove elements in an array based on their odd or even index? 尝试根据它们是偶数还是奇数来将数组中的值相乘 - trying to multiply values in array based on if they are even or odd 特殊数组:如果每个偶数索引包含一个偶数并且每个奇数索引包含一个奇数,则该数组是特殊的 - Special Array: An array is special if every even index contains an even number and every odd index contains an odd number 将数组值转换为对象,根据索引位置添加键 - convert array values to object, add keys based on index position 根据getDay对象JavaScript显示文本“ Even Day”或“ Odd Day” - Display text “Even Day” or “Odd Day” based on getDay object JavaScript 基于另一个数组的奇数和偶数索引的元素创建数组 - create arrays based on elements of odd and even indexes of another array 基于奇数/偶数位置将数组拆分为两个数组 - split an array into two arrays based on odd/even position 有没有办法对 Javascript 中的数组中的每个奇数和偶数 object 进行排序? - Is there a way to sort each odd and even object in an array in Javascript? 将对象转换为数组保留索引 - Convert object to array preserving index 函数从数组中返回项,其中奇数索引的项按其前偶索引处的数字重复 - Function to return items from an array where items at odd index which are repeated by the number at its preceding even index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM