将嵌套数组转换为对象

时间:2018-08-24 15:27:47

标签: javascript arrays javascript-objects

我正在尝试使用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"]
}

7 个答案:

答案 0 :(得分:9)

使用foreach的时间更短

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

var bookpriceObj = {};


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

console.log(bookpriceObj)

答案 1 :(得分:4)

您可以将reduce与Array Destructoring一起使用。

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

正在发生的事情:

  • a是累加器,其最终参数的初始值传递给reduce。我们传递的最后一个值是{},所以它是一个对象
  • 数组解构可以立即将数组中的值分配给变量。 a.e. [a, b] = ["one", "two"]a赋值为"one",而b赋值为"two"
  • 对于每个项目的每次迭代,我们都将b(ae“ book1”)的值分配为对象(a)上的属性,并赋予其等于c的值(“ $ 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)

答案 2 :(得分: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已经在数组上进行了迭代。

答案 3 :(得分: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);

答案 4 :(得分: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;
}, {});

答案 5 :(得分:0)

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

答案 6 :(得分: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);