I've been trying to figure for quite a while on populating my 2D array to object. I tried using _.map()
, but it did not gave me the result I was expecting.
I have an array that is stored:
// My array
var myArray = [ [foo, bar, fiz], [faz, far, fee] ];
// My object
var myObject = {
key1: {
val1: 1,
val2: 2,
val3: 3
},
key2: {
val1: 1,
val2: 2,
val3: 3
}
}
And the result I am trying to achieve is:
var myObject = {
key1: {
val1: foo,
val2: bar,
val3: fiz
},
key2: {
val1: faz,
val2: far,
val3: fee
}
}
Here what I got so far:
_.map(myObj, x => {
for (var i = 0; myArray.length; i++) {
x.val1 = myArray[i][0];
x.val2 = myArray[i][1];
x.val3 = myArray[i][2];
}
}
The issue I encountered with _.map()
I want it to iterate only one time. Since the length of array and object is the same, I don't think is necessary to iterate twice. Unfortunately my array does not have a key which I can use it to distinguish, or else I would have used Object.assign()
.
Since the object's original values are discarded, and the keys of the object can be reproduced easily, you can build the object from the array using 2 Array#reduce methods:
var myArray = [ ['foo', 'bar', 'fiz'], ['faz', 'far', 'fee'] ]; var myObject = myArray.reduce(function(obj, arr, i) { obj['key' + (i + 1)] = arr.reduce(function(o, item, j) { o['val' + (j + 1)] = item; return o; }, {}); return obj; }, {}); console.log(myObject);
For a conversion, you need a double nested loop for each array. Then generate the key and build the object and content.
var array = [['foo', 'bar', 'fiz'], ['faz', 'far', 'fee']], object = {}; array.forEach(function (a, i) { var key = 'key' + (1 + i); object[key] = object[key] || {}; a.forEach(function (b, j) { object[key]['val' + (1 + j)] = b; }) }); console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
For variable keys, you could use some arrays with the keys and take it for the outer and inner level.
var array = [['foo', 'bar', 'fiz'], ['faz', 'far', 'fee']], topKeys = ['key1', 'key2'], subKeys = ['val1', 'val2', 'val3'], object = {}; array.forEach(function (a, i) { object[topKeys[i]] = object[topKeys[i]] || {}; a.forEach(function (b, j) { object[topKeys[i]][subKeys[j]] = b; }) }); console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.