Reputation: 43
I am looping to convert the array of array to object, but the final object has only the last item in the object. I am getting confused because you cant push in an object like array, and the number of loop is getting me frustrated. need help
here is the JSbin : http://jsbin.com/torawovicu/edit?js,console
Also how to get the object the same order as the array?
this is what the result should look like:
var newResult =
[
{itemcode: 1, item: 'Pen', 'cashier' : 'Sam'},
{itemcode: 2, item: 'Eraser', 'cashier' : 'Kim'}
]
Here is my code
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
]
//console.log(people.length);
function result(array) {
var newObj = {};
var newArr = [];
for (var x in array) {
//console.log(array[x])
var item = array[x];
for (var y in item) {
var itemSingle = item[y]
//console.log(itemSingle);
for (i = 0; i < itemSingle.length; i = i + 2) {
newObj[itemSingle[i]] = itemSingle[i + 1];
}
}
}
return newObj;
}
console.log(result(list));
Upvotes: 2
Views: 739
Reputation: 6674
You have to use one loop to iterate over main array and then run loops to iterate over each array item (which also is an array) to construct object with properties you need. You can use map
as main loop to return new array with items constructed inside each iteration. To construct those items you can use forEach
:
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
function result(array) {
let newArray = array.map(function(nestedArray) {
let obj = {};
nestedArray.forEach(function(item) {
obj[item[0]] = item[1];
});
return obj;
});
return newArray;
}
console.log(result(list));
Upvotes: 2
Reputation: 12458
Your question could possibly be addressed by using a relatively recent feature in JavaScript: map objects.
Note that when you have an array of indeterminate length where each element is itself an array that is two elements long, you can convert the outer array into a map object instead of just a plain object. e.g. const newMapObj = new Map([['a', 1], ['b', 2]]);
. Entering that into a terminal and then checking console.log(newMapObj)
produces the following: Map { 'a' => 1, 'b' => 2 }
. In your example, you could do this with each of your two list
elements/store items, i.e. you would end up with an array of 2 map objects.
Such map objects have some convenient features, such as get
and has
. Some people also find them frustrating because of e.g. a lack of some helpful methods used with, say, arrays, like, um, well, the map
method. (Note that the map
method on arrays and the map/Map
data object type are two completely different things. I know, it's confusing.)
The code snippet below creates an array of such map objects, one for each outer array element (i.e. one for each store 'item'), with one simple line:
const newResult = list.map(a => new Map(a));
Unfortunately, at this point in time at least, the code snippet tool here on Stack Exchange doesn't allow us to simply show the map object using console.log
the way you can with, say, a plain object or an array. As a 2nd best substitute, the code snippet below logs out some of the results of using the map objects, just to demonstrate that the map objects were in fact created.
When I do the same thing in a Mac terminal (i.e. define list
as the nested arrays in your question and then calculate newResult
as above), console.log(newResult)
shows the following:
[ Map { 'itemCode' => 1, 'item' => 'Pen', 'cashier' => 'Sam' },
Map { 'itemCode' => 2, 'item' => 'Eraser', 'cashier' => 'Kim' } ]
In other words, it is an array of map objects instead of an array of objects.
If you're interested in this recent JavaScript feature, you should check out the MDN documentation on the Map data object.
Whether you really want to use map objects or plain objects depends on your use case. The MDN documentation linked above has a short section to help you determine whether you want to use map objects or plain objects.
const list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
const newResult = list.map(a => new Map(a));
console.log('The name for the 1st item is:', newResult[0].get('item'));
console.log('The cashier for the 2nd item is:', newResult[1].get('cashier'));
Upvotes: 0
Reputation: 12458
You can do it with a single line:
const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));
const show = msg => {console.log(JSON.stringify(msg));};
const list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));
show(newResult);
Upvotes: 1
Reputation: 31692
You can use Array.prototype.map and Array.prototype.reduce to get the desired result like this:
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
function result(arr) {
return arr.map(function(sub) {
return sub.reduce(function(acc, e) {
acc[e[0]] = e[1];
return acc;
}, {});
})
}
console.log(result(list));
Note: you can't relly on the order of the object poperties.
Upvotes: 2
Reputation: 51
You will have to use 2 dimensional array for that, first you have to create one for comlumn and second for row, in example i have shown in comulmn i have added the name, and in row i have added occupation, let's code :-
data = new Array(5)
info = [0] = new Array(2)
name [0][0] = "Tom"
occu [0][1] = "Worker"
info [1] = new Array(2)
name [1][0] = "Beryl"
occu [1][1] = "engineer"
info [2] = new Array(2)
name [2][0] = "Ann"
occu [2][1] = "surgeon"
info [3] = new Array(2)
occu [3][0] = "Bill"
name [3][1] = "taxman"
info [4] = new Array(2)
name [4][0] = "Myrtal"
occu [4][1] = "bank robber"
Upvotes: -1
Reputation: 781059
There are two problems.
First, you're never adding the objects to the array or returning the array, you're just returning the object.
Second, you're using the same object each time through the loop, just replacing its properties. You need to create a new object each time, and then add it to the array.
It's also not a good idea to use for-in
to iterate an array, use a numeric for
loop (or the Array.prototype.forEach()
function). See Why is using "for...in" with array iteration a bad idea?
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
]
//console.log(people.length);
function result(array) {
var newArr = [];
for (var x = 0; x < array.length; x++) {
var newObj = {};
var item = array[x];
for (var y = 0; y < item.length; y++) {
var itemSingle = item[y];
for (var i = 0; i < itemSingle.length; i+=2) {
newObj[itemSingle[i]] = itemSingle[i + 1];
}
}
newArr.push(newObj);
}
return newArr;
}
console.log(result(list));
Upvotes: 1