如何在javascript中将数组转换为对象

时间:2017-03-30 14:48:40

标签: javascript arrays object

我有一个这样的数组:

[
{ id: “Идент”, name: “Назв”, price: “Сто”, quantity: “Коло” },
[ 1, “продукт 1”, “400”, 5 ],
[ 2, “продукт 2”, “300”, 7 ],
[ 2, “продукт 2”, “300”, 7 ]]

如何将其转换为以下内容:

{
    items: [
        { name: "Хлеб", id: 1, price: 15.9, quantity: 3 },
        { name: "Масло", id: 2, price: 60, quantity: 1 },
        { name: "Картофель", id: 3, price: 22.6, quantity: 6 },
        { name: "Сыр", id: 4, price:310, quantity: 9 }
    ]
};

2 个答案:

答案 0 :(得分:1)

我假设索引0:id,1:name,2:price,3:quantity。你去吧,

var array = [
         [12,"abc",232,2],
         [12,"abc",232,2],
         [12,"abc",232,2],
         [12,"abc",232,2]
       ];
       var obj = {};
       obj.options  = (function(array){
          var e = [];
          for(i in array){
            t = {};
            t.id = array[i][0];
            t.name = array[i][1];
            t.price = array[i][2];
            t.quantity = array[i][3];
            e.push(t);
          }
          return e;
       })(array);
       console.log(obj)

答案 1 :(得分:1)

要将包含数据的数组转换为带有对象的数组,可以使用带有键的另一个数组,并迭代它以分配新对象的属性。



var data = [{ id: 'id', name: 'name', price: 'price', quantity: 'quantity' }, [0, 'foo', 1.99, 201], [1, 'abc', 2.5, 42], [2, 'baz', 10, 99], [6, 'bar', 21.99, 1]],
    keys = Object.keys(data[0]),        
    result = {
        items: data.slice(1).map(function (a) {
            var temp = {};
            keys.forEach(function (k, i) {
                temp[k] = a[i];
            });
            return temp;
        })
    };
    
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }