javascript batch add keys - javascript

I want to set multiple keys of array in javascript ,
but code like this was so ugly. but only this can work right.
var listData = [];
listData['today'] = [];
listData['data1'] = [];
listData['data2'] = [];
listData['data3'] = [];
listData['data4'] = [];
listData['data5'] = [];
listData['data6'] = [];
listData['data6'] = [];
i try this to init array
function initArray(arr, keys, defaultValue) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
delete arr[key];
arr[key] = defaultValue;
}
return arr;
}
But after setting the array,
i put data in it by
listData['data1'].push(datalist[i].num)
listData['data2'].push(datalist[i].num)
.
returns all the same data1 and data2 in array.
hope someone can help about this batch add keys to array.

Try modifying this push method.
var listData = [];
var keys = [ 'today', 'data', 'daata' ];
initObject(keys);
function initObject(params) {
for (i=0; i<params.length; i++) {
var x = params[i]
listData.push(x)
}
}

Use an object instead of an array:
var listData = {};
var keys = ['today', 'data1', 'data2'];
function initObject(obj, keys, defaultValue) {
keys.forEach(key => {
obj[key] = [];
})
return obj;
}
console.log(initObject(listData, keys, []));

Related

Convert JSON to list of arrays

How can I convert my JSON to a list of arrays
My JSON is Serie :
[{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}]
I would like this format:
[[10,2],[20,3],[:51,1]]
Here's my code so far:
var linq = Enumerable.From(rows);
var Serie = linq
.GroupBy("$.Year", null,
function(key, g) {
var result = {
Value: g.Sum("$.Car"),
ValuePourcent: g.Sum("$.CarPourcent")/Total*100,
};
return result;
})
.ToArray()
A simple for loop does the trick:
var data = [
{"Value":10,"ValuePourcent":2},
{"Value":20,"ValuePourcent":3},
{"Value":51,"ValuePourcent":1}
];
var result = [];
for (var i = 0; i < data.length; i++) {
var datum = data[i];
result.push([datum.Value, datum.ValuePourcent]);
}
console.log(result);
You can try to loop through the json array like this:
var json = JSON.parse("[{\"Value\":10,\"ValuePourcent\":2},{\"Value\":20,\"ValuePourcent\":3},{\"Value\":51,\"ValuePourcent\":1}]");
var newArray = [];
for(var i = 0; i < json.length; i++) {
newArray.push([
json[i].Value,
json[i].ValuePourcent
]);
}
You can use map
dataArray = [{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}]
newFormat = dataArray.map(function(e){
return [e["Value"], e["ValuePourcent"]]
});
var json = [{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}];
var data = $.parse(JSON(json))
var array = [];
var keys = Object.keys(json);
keys.forEach(function(key){
array.push(json[key]);
array.push(data[key]
});

Simplification of multi level object array in JavaScript

I have a JavaScript array:
var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];
I want it to convert to:
[{"abc":"vf","a":"1","b":"3"},{"abc":"vf","a":"2","b":"4"}]
I have written the JavaScript code for it:
Javascript:
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
var globalResultArr = [];
var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];
function f(){
for(var i=0;i<data.length;i++){ //Iterate Data Array
var obj = data[i];
var resultArray = [{}];
for (var key in obj) { // Iterate Object in Data Array
if (obj.hasOwnProperty(key)) {
if(Object.prototype.toString.call(obj[key]) === "[object Array]"){
var tempRes = $.extend(true, [], resultArray);
resultArray = [];
for(var k=0;k<tempRes.length;k++){
var tempResObj = tempRes[k];
for(var j=0;j<obj[key].length;j++){ // If it has array, then iterate it as well
var innerObj = obj[key][j]; //Iterate Object in inner array
for(var innerkey in innerObj){
if (innerObj.hasOwnProperty(innerkey)) {
tempResObj[innerkey] = innerObj[innerkey];
}
}
resultArray.push(tempResObj);
}
}
}else{
for(var i=0;i<resultArray.length;i++){
resultArray[i][key] = obj[key];
}
}
}
}
globalResultArr.pushArrayMembers(resultArray);
}
document.getElementById("test").innerHTML = JSON.stringify(globalResultArr);
}
f();
HTML:
<div id="test"></div>
Issue is that browser crashes when item in data array > 10000. How can i make this work? Is there any simpler approach?
JSFiddle
Here's an attempt. It assumes there is only one property in each object that is an array. It them composes an object with the remaining properties and makes a new clone with each value from the array property.
* Works as required now *
var resultArray = [],
len = data.length,
tempObj,
newObj,
targetVal,
targetKey,
composeObj,
tempJson,
key,
i, k;
for(i = 0; i < len; i++) {
tempObj = data[i];
// obj to build up
composeObj = {};
// look at all key/vals in obj in data
for(key in tempObj) {
keyObj = tempObj[key];
// is it an array?
if(Array.isArray(keyObj)) {
// save key/val for array property
targetVal = keyObj;
targetKey = key;
}
else {
// copy non-array properties to empty object
composeObj[key] = keyObj;
}
}
// json-ify the object for cloning
tempJson = JSON.stringify(composeObj);
// compose new object for each val in array property
targetVal.map(function(val) {
// clone object
newObj = JSON.parse(tempJson);
// add array values as object properties
for(k in val) {
newObj[k] = val[k];
}
// add to results
resultArray.push(newObj);
});
}

How to build an array from a string in javascript?

I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo

rearrange Array according to values order of another Array

I have two arrays like below
var arr = ["x", "y", "z", "a", "b", "c"];
var tgtArr = [{val:"a"}, {val:"b"}]; It does not need to be as lengthy as Array `arr`
This is what I have tried
var dest = new Array(arr.length);
for(var i = 0; i < arr.length; i++){
for(var k = 0; k < tgtArr.length; k++){
dest[i] = dest[i] || [];
if(tgtArr[k].val == arr[i]){
dest[i] = arr[i];
}
}
}
console.log(dest);
My Expected output is (for above tgtArr value)
[{}, {}, {}, {val:"a"}, {val:"b"}, {}];
if tgtArr is empty Array
[{},{},{},{},{},{}]
Here is the fiddle. Any alternative for this, it seems not a good way to me as I am iterating through the entire array everytime.
Short:
var result = arr.map(function(x) {
return tgtArr.some(function(o) { return o.val == x; }) ? {val:x} : {};
});
This is more efficient:
var set = {};
tgtArr.forEach(function(obj, i) {
set[obj.val] = true;
});
var result = arr.map(function(x) {
return x in set ? {val:x} : {};
});
This is the same as Paul's answer, but with a loop instead of map. It collects the keys first based on the val property, then creates a new array either with empty objects if the key isn't in tgtArr, or copies a reference to the object from tgtArr if it is:
function newArray(arr, tgtArr) {
var keys = {},
i = tgtArr.length,
j = arr.length,
newArr = [];
// Get keys
while (i--) keys[tgtArr[i].val] = tgtArr[i];
// Make new array
while (j--) newArr[j] = arr[j] in keys? keys[arr[j]] : {};
return newArr;
}
It should be efficient as it only traverses each array once.
var dest = new Array(arr.length);
for(var i = 0; i < arr.length; i++){
dest[i] = {}
for(var k = 0; k < tgtArr.length; k++){
if(tgtArr[k].val == arr[i]){
dest[i] = tgtArr[k];
}
}
}
console.log(dest);
I like using map rather than loops for this kind of thing (Fiddle):
var result = arr.map(function(x) {
var match = tgtArr.filter(function(y) {
return y.val == x;
});
if (match.length == 1) return match[0];
else return {};
});
This is a possibly inefficient, in that it traverses tgtArr for every item in arr, so O(n*m). If needed, you could fix that by pre-processing tgtArr and converting it to a hash map (Fiddle). This way you've got an O(n+m) algorithm (traverse each array once):
var tgtMap = {};
tgtArr.forEach(function(x) { tgtMap[x.val] = x; })
var result = arr.map(function(x) {
var match = tgtMap[x];
return match || {};
});
var tmp = {};
for (var i = 0; i < tgtArr.length; i++) {
tmp[tgtArr[i].val] = i;
}
var dest = [];
for (var i = 0; i < arr.length; i++) {
var obj= tmp[arr[i]] === undefined ? {} : tgtArr[tmp[arr[i]]];
dest.push(obj);
}
DEMO

Merge objects in arrays in Javascript

I have three objects in two arrays:
var tab1 = [{"foo":"bar"}, {"foo2":"bar2"}, {"foo3":"bar3"} ];
var tab2 = [ {"2foo":"2bar"}, {"2foo2":"2bar2"}, {"2foo3":"2bar3"} ];
My goal is merge that arrays like this:
var tab3 = [ {"foo":"bar", "2foo":"2bar"}, {"foo2":"bar2",
"2foo2":"2bar2"}, {"foo3":"bar3", "2foo3":"2bar3"} ];
How can I do this?
If you're using jQuery, you can use jQuery.extend().
It does exactly what you want.
Example:
for (var i = 0; i < tab1.length; i++) {
tab1[i] = $.extend(tab1[i], tab2[i]);
}
Here's a fiddle: http://jsfiddle.net/fCx9C/2/
If you don't want to use jQuery, you can see how they implement jQuery.extend() here.
If you do want to use jQuery, here's the jQuerified loop:
$.each(tab1, function (i, t) {
t = $.extend(t, tab2[i]);
});
Demo
function merge(obj1, obj2) {
var tmp = {};
for (var key in obj1) {
tmp[key] = obj1[key];
};
for (key in obj2) {
tmp[key] = obj2[key];
};
return tmp;
};
function zip(arr1, arr2) {
var tmp = [];
for (var i = 0, len = arr1.length; i < len; i++) {
tmp[i] = merge(arr1[i], arr2[i]);
};
return tmp;
};
var tab1 = [{"foo":"bar"}, {"foo2":"bar2"}, {"foo3":"bar3"} ];
var tab2 = [ {"2foo":"2bar"}, {"2foo2":"2bar2"}, {"2foo3":"2bar3"} ];
console.log(zip(tab1, tab2));
This should do what you want:
var merge = function(t1, t2) {
var arr = [];
for(i=0; i<t1.length; i++) {
for(var prop in t2[i]) {
arr.push(t1[i]);
arr[i][prop] = t2[i][prop];
}
}
return arr;
}
var tab3 = merge(tab1, tab2);
This can be done in vanilla JavaScript quite nicely:
var tab1 = [{"foo":"bar"}, {"foo2":"bar2"}, {"foo3":"bar3"} ];
var tab2 = [ {"2foo":"2bar"}, {"2foo2":"2bar2"}, {"2foo3":"2bar3"} ];
var tab3 = [];
for(var i = 0; i < 3; i++) {
for(var j in tab2[i]) {
tab1[i][j] = tab2[i][j];
}
tab3.push(tab1[i]);
}
console.log(tab3);
However, you don't even have to create a tab3 array as it puts everything nicely into tab1 already.

Categories