Efficient Way To Create Javascript Object From Array Of Properties And Array Of Matching Property Values
Is it possible to create the the data1 array without using nested for loops? // My starting Normalized data var fields = ['name','age']; var data2 = [['John',20],['Tom',25]];
Solution 1:
var fields = ["name","age"];
var data2 = [["John",20],["Tom",25]];
var data1 = data2.map(function(arr){
var obj = {};
arr.forEach(function(val, ind){ obj[fields[ind]] = val; });
return obj;
});
but it is basically nest loops.
Solution 2:
Or you could start getting acquainted with Javascript tools like the underscore/lodash libraries that offer a lot of utilities functions for cases like this.
For example, using _.zipObject() offered by lodash:
fields = ["name", "age"];
data2 = [["John", 20],["Tom", 25]];
res = [];
data2.forEach(function(arr) {
res.push(_.zipObject(fields, arr));
});
In essence as @epascarello mentioned, you are still doing a double loop. It's just more elegant (subject always to coding taste) and more compact.
Solution 3:
No loops...
Baca Juga
var data1 = [];
data1.push(eval('({"' + fields[0] + '":"' + data2[0][0] +
'","' + fields[1] + '":' + data2[0][1] + '})'));
data1.push(eval('({"' + fields[0] + '":"' + data2[1][0] +
'","' + fields[1] + '":' + data2[1][1] + '})'));
Guess it depends on your definition of efficient.
Solution 4:
Another implementation using native map and reduce (which will be nested loops - but figured I'd throw it in as another option):
var data1 = data2.map(function(currentArray, index){
return currentArray.reduce(function(objToReturn, currentValue, index){
objToReturn[fields[index]] = currentValue;
return objToReturn;
},{});
});
Solution 5:
I finally thought of an efficient way that doesn't use nest for loops! :)
var fields = ["name","age"];
var data2 = [["John",20],["Tom",25]];
var body = "";
for(var i = 0; i < fields.length; i++){
body = body.concat("this."+fields[i] +"=args["+i+"]; ");
}
var model = newFunction("args",body);
var data1 = [];
for(var i = 0; i < data2.length; i++){
var x = new model(data2[i]);
data1.push(x);
}
Post a Comment for "Efficient Way To Create Javascript Object From Array Of Properties And Array Of Matching Property Values"