0

I have an array like this:

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

How can I transform it into something like this:

{
    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
  • 4
    how do you match produkt with kartofel? Commented Mar 30, 2017 at 14:53
  • Your array has different data, compared with your expected output...apart from that, this is an easy task.... Commented Mar 30, 2017 at 14:53

2 Answers 2

1

I assume that index 0:id,1:name,2:price,3:quantity. here you go,

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)
Sign up to request clarification or add additional context in comments.

Comments

1

To convert an array with data to an array with objects, you could use another array with keys and iterate it for the assignment of the properties for the new objects.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.