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 }
]
};
Cœur
39k25 gold badges207 silver badges282 bronze badges
-
4how do you match produkt with kartofel?Nina Scholz– Nina Scholz2017年03月30日 14:53:02 +00:00Commented Mar 30, 2017 at 14:53
-
Your array has different data, compared with your expected output...apart from that, this is an easy task....Hackerman– Hackerman2017年03月30日 14:53:21 +00:00Commented Mar 30, 2017 at 14:53
2 Answers 2
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)
answered Mar 30, 2017 at 15:03
not_python
9126 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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; }
answered Mar 30, 2017 at 21:02
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Comments
lang-js