简体   繁体   English

将嵌套数组转换为对象

[英]Convert nested array to an object

I am trying to use reduce to convert a nested array to an object. 我试图使用reduce将嵌套数组转换为对象。

I want to convert var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]]; 我想转换var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];

to

var bookpriceObj = {
    "book1": "$5", 
    "book2": "$2",
    "book3": "$7"
};

here is what I tried 这是我试过的

var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
bookpriceObj = {};
bookprice.reduce(function(a, cv, ci, arr){
    for (var i = 0; i < arr.length; ++i)
        bookpriceObj [i] = arr[i];

    return bookpriceObj ;
})

but the below result is not the desired result 但是以下结果并不是理想的结果

{
    ["book1", "$5"]
    ["book2", "$2"]
    ["book3", "$7"]
}

Using forEach is shorter 使用forEach更短

 var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]]; var bookpriceObj = {}; bookprice.forEach(e=>bookpriceObj[e[0]] = e[1]); console.log(bookpriceObj) 

You can use reduce with Array Destructoring. 您可以使用reduce with Array Destructoring。

    bookpriceObj = bookprice.reduce((a, [b, c]) => (a[b] = c, a), {});

Here's what's happening: 这是发生了什么:

  • a is the accumulator which has an initial value of the final parameter passed to reduce . a是累加器,它具有传递给reduce的最终参数的初始值。 The last value we pass is {} so it's an object 我们传递的最后一个值是{}所以它是一个对象
  • Array Destructoring can immediately assign values in an array to variables. Array Destructoring可以立即将数组中的值赋给变量。 ae [a, b] = ["one", "two"] assigns a with a value of "one" and b with a value of "two" ae [a, b] = ["one", "two"]赋值a"one"b赋值为"two"
  • with each iteration over each item we assign the value of b (ae "book1") as a property on the object( a ) and give it a value equal to c (ae "$2") 对每个项目进行每次迭代,我们将b (ae“book1”)的值赋值为对象( a )的属性,并赋予它一个等于c (ae“$ 2”)的值
  • Each iteration of reduce you must return the accumulator( a ) 每次迭代reduce你必须返回累加器( a
  • When the whole thing is finally done, it'll store in bookpriceObj the result! 当整个事情终于完成时,它将存储在bookpriceObj的结果!

 var bookprice = [ ["book1", "$5"], ["book2", "$2"], ["book3", "$7"]], bookpriceObj = bookprice.reduce((a, [b, c]) => (a[b] = c, a), {}); console.log(bookpriceObj) 

You need to return an object from the "reducer" AKA the first argument of reduce, and use an empty object as second argument. 您需要从“reducer”AKA返回一个对象,即reduce的第一个参数,并使用空对象作为第二个参数。

 var bookprice = [ ["book1", "$5"], ["book2", "$2"], ["book3", "$7"] ]; var result = bookprice.reduce(function(object, el) { object[el[0]] = el[1] return object; }, {}) console.log(result) 

You don't need a for loop since reduce already iterates over the array. 您不需要for循环,因为reduce已遍历数组。

Using Array.reduce() , Array destructuration , Dynamical keys and Spread operator . 使用Array.reduce()Array destructurationDynamical keysSpread operator

 const bookprice = [ ['book1', '$5'], ['book2', '$2'], ['book3', '$7'], ]; const ret = bookprice.reduce((tmp, [ name, price, ]) => ({ ...tmp, [name]: price, }), {}); console.log(ret); 

You are not returning the accumulated object in your reduce function and the for loop is not necessary. 您没有在reduce函数中返回累积的对象,并且不需要for循环。

Try: 尝试:

const bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
const nameIndex = 0;
const priceIndex = 1;

const bookPricesObj = bookprice.reduce((prices, bookInfo) => {
    const name = bookInfo[nameIndex];
    const price = bookInfo[priceIndex];

    prices[name] = price;
    return prices;
}, {});
bookprice.reduce((acc, price) => {
  let tmp = {}
  tmp[price[0]] = price[1]
  return Object.assign(acc, tmp)
}, {})

using Array.prototype.reduce to convert a nested array to an object 使用Array.prototype.reduce将嵌套数组转换为对象

 var bookprice = [ ["book1", "$5"], ["book2", "$2"], ["book3", "$7"] ]; bookpriceObj = bookprice.reduce(function(acc, cur, i) { acc[cur[0]] = cur[1]; return acc; }, {}) console.log(bookpriceObj); 

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

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