将嵌套数组转换为对象

问题描述 投票:6回答:7

我试图使用reduce将嵌套数组转换为对象。

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

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

这是我试过的

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

但是以下结果并不是理想的结果

{
    ["book1", "$5"]
    ["book2", "$2"]
    ["book3", "$7"]
}
javascript arrays javascript-objects
7个回答
9
投票

使用forEach更短

var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];

var bookpriceObj = {};


bookprice.forEach(e=>bookpriceObj[e[0]] = e[1]);

console.log(bookpriceObj)

4
投票

您可以使用reduce with Array Destructuring。

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

这是发生了什么:

  • a是累加器,它具有传递给reduce的最终参数的初始值。我们传递的最后一个值是{},所以它是一个对象
  • Array Destructoring可以立即将数组中的值赋给变量。酸当量[a, b] = ["one", "two"]指定a的值为"one"b,其值为"two"
  • 对每个项目进行每次迭代,我们将b(a.e。“book1”)的值赋值为对象的属性(a),并给它一个等于c的值(a.e。“$ 2”)
  • reduce的每次迭代你必须返回累加器(a
  • 当整个事情最终完成时,它将存储在bookpriceObj结果!

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

console.log(bookpriceObj)

3
投票

您需要从“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)

您不需要for循环,因为reduce已遍历数组。


1
投票

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

1
投票

您没有在reduce函数中返回累积的对象,并且不需要for循环。

尝试:

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;
}, {});

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

0
投票

使用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);
© www.soinside.com 2019 - 2024. All rights reserved.