converting array of array into array of keyvalue pairs - javascript

I want to convert array of array into array of key-value pairs using javascript or jquery.
i have array of array like :
var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];
how do i convert arrOfarr into the array of key-value pairs that looks like
[{id:1,text:'One'},{id:2,text:'Two'},{id:3,text:'Three'}]

var result = [];
for (var i = 0, iLength = arrOfarr.length; i < iLength; i++) {
result.push({ id: arrOfarr[i][0], text: arrOfarr[i][1] });
}
console.log(result);

you can use $.map()
arrOfarr = jQuery.map(arrOfarr, function(val){
return {id: val[0], text: val[1]}
})
Demo: Fiddle

var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];
var hash = new Array(arrOfarr.length);
for (var x = 0; x < hash.length; x++) {
hash[x] = {id: arrOfarr[x][0], text: arrOfarr[x][1]};
}
This might help you with performance if you have a large array or a lot of arrays because it'll allocate the size of the array in advance.

var result = [];
for(var i = 0; i < arrOfarr.length; i++){
var ar = arrOfarr[i];
result.push({ id: ar[0], text: ar[1] });
}

You can;
var arr = [[1,'One'],[2,'Two'],[3,'Three']];
var o = []
for (var i = 0; i < arr.length; i++)
{
o.push({id: arr[i][0], text: arr[i][1]});
}

try this,
a=[[1,'one'],[2,'two'],[3,'three']];
$.each(a,function(id,value){
a[id]={id:value[0],text:value[1]};
});
now a will have three objects as you want.

Related

JavaScript: How do I avoid an "undefined" error when assigning object property values to an array? [duplicate]

I need to create an array of object literals like this:
var myColumnDefs = [
{key:"label", sortable:true, resizeable:true},
{key:"notes", sortable:true,resizeable:true},......
In a loop like this:
for (var i = 0; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
}
The value of key should be results[i].label in each element of the array.
var arr = [];
var len = oFullResponse.results.length;
for (var i = 0; i < len; i++) {
arr.push({
key: oFullResponse.results[i].label,
sortable: true,
resizeable: true
});
}
RaYell's answer is good - it answers your question.
It seems to me though that you should really be creating an object keyed by labels with sub-objects as values:
var columns = {};
for (var i = 0; i < oFullResponse.results.length; i++) {
var key = oFullResponse.results[i].label;
columns[key] = {
sortable: true,
resizeable: true
};
}
// Now you can access column info like this.
columns['notes'].resizeable;
The above approach should be much faster and idiomatic than searching the entire object array for a key for each access.
You can do something like that in ES6.
new Array(10).fill().map((e,i) => {
return {idx: i}
});
This is what Array#map are good at
var arr = oFullResponse.results.map(obj => ({
key: obj.label,
sortable: true,
resizeable: true
}))
This will work:
var myColumnDefs = new Object();
for (var i = 0; i < oFullResponse.results.length; i++) {
myColumnDefs[i] = ({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}
In the same idea of Nick Riggs but I create a constructor, and a push a new object in the array by using it. It avoid the repetition of the keys of the class:
var arr = [];
var columnDefs = function(key, sortable, resizeable){
this.key = key;
this.sortable = sortable;
this.resizeable = resizeable;
};
for (var i = 0; i < len; i++) {
arr.push((new columnDefs(oFullResponse.results[i].label,true,true)));
}
If you want to go even further than #tetra with ES6 you can use the Object spread syntax and do something like this:
const john = {
firstName: "John",
lastName: "Doe",
};
const people = new Array(10).fill().map((e, i) => {(...john, id: i});
I'd create the array and then append the object literals to it.
var myColumnDefs = [];
for ( var i=0 ; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}
var myColumnDefs = new Array();
for (var i = 0; i < oFullResponse.results.length; i++) {
myColumnDefs.push({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}

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]
});

how to loop through array of arrays and combine values

I need to loop through a array of arrays and calculate the sum of each array. The Json is a kendo-ui chart series with arrays of x,y coordinates. I need to return the sum of the x,y values. linq.js or javascript will work. thanks
JSON
var =series = [{
"style":"smooth",
"color":"blue",
"data":[
[600,30000],
[800,60000],
[1100,100000]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
So for this example i would need to end up with this
var newSeries = [{
"style":"smooth",
"color":"blue",
"data":[
[30600],
[60800],
[101100]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
for(var i=0;i<series[0].data.length;i++){
var val = series[0].data[i];
newSeries.data[i] = val[0] + val[1];
}
You can use loop and use reduce
var series = [{
...
}]
for (var i = 0; i < series.length; i++) {
for (var j = 0; j < series[i].data.length; j++) {
series[i].data[j] = series[i].data[j].reduce(function(p,c) {
return p + c;
});
}
}
Demo: http://jsfiddle.net/kv854c61/1/
you just need to loop the values in your data properties something like this..
for( var i - 0; i < series.length-1; i++){
for( var j - 0; j < series[i].data.length-1; i++){
var result = series[i].data[j][0] + series[i].data[j][1];
series[i].data[j] = result;
}
}
now it would make sense to add the new data array, so as not to overwrite
series[i].new_data[j] = result;
Array.map is quite useful in this case:
// extracts the data entries of each item in the series
var data = series.map(function(item){ return item["data"]; });
function sum(point) {
return point[0] + point[1];
// in case point is of arbitrary dimension use Array.reduce:
// return point.reduce(function(prev, cur){ return prev + cur; }, 0);
}
var sums = data.map(function(arr){
return arr.map(function(point){
return sum(point);
});
});
// sums now contains an array of array of sums
// e.g. [[30600,60800,101100]]

JavaScript making an array of key value object from a string

I have a string like this
var information = 'name:ozil,age:22,gender:male,location:123 street';
I want to make an array of key value object like this
var informationList=[
{
'key':'name',
'value':'ozil'
},
{
'key':'gender',
'value':'male'
},
{
'key':'location',
'value':'123 street'
},
]
Using split and map:
var information = 'name:ozil,age:22,gender:male,location:123 street',
result = information.split(',').map(function(item){
var arr = item.split(':');
return {
key: arr[0],
value: arr[1]
}
});
document.write(JSON.stringify(result));
You can try this:
var list = [];
var pairs = information.split(',');
for (var i = 0; i < pairs.length; i++) {
var p = pairs[i].split(':');
list.push({
key: p[0],
value: p[1]
});
}
This should do it:
var input = "name:ozil,age:22,gender:male,location:123 street";
var temp = input.split(",");
var result = [];
for(var i=0; i < temp.length; i++) {
var temp2 = temp[i].split(":");
result.push({key:temp2[0], value:temp2[1]});
}
console.log(result);
result now contains what you specified.

JSON Assoc Array to Variables?

I have a JSON associate array
[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
and I want to make it so that it becomes an array where
{
theatre = Test
time = 5:00pm
},
{
theatre = Testing2
time = 4:30 pm
}
But I can't figure out how to take a key name and make it a value...
Any help? I was looking at Object.keys but I couldn't find a suitable solution.
You have an array with object values. You'd need to loop over them:
var oldArray = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
var newArray = [];
for (var i = 0; i < oldArray.length; i++) {
var keys = Object.keys(oldArray[i]);
newArray.push({
theatre: keys[0],
time: oldArray[i][keys[0]]
});
}
http://jsfiddle.net/FNAtw/
This will give you an array stored in newArray with two elements. The first element is an object with kvps theatre: 'Test' and time: '5:00pm'. The second element is an object with kvps theatre: 'Testing2' and time: '4:30pm'.
Try this workaround:
var json = '[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]';
var betterJson = json.replace('{"', '{"theatre":"').replace('":"','",time:"');
If the JSON is always as simple as above, then this should work. But it's brittle...
If you have a JS object, you could use Object.keys. That will work in the latest browsers.
You can also loop each item and just save the 1st item.
var result = [];
var str = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
for (var i = 0; i < str.length; i++) {
var obj = {};
foreach (var key in str[i]) {
obj.theatre = key;
obj.time = str[i][key];
}
result.push(obj);
}
May be a bit clunky, BUT should work cross-browser.
var js = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
var newJSON = []
for(var i = 0; i< js.length; i++) {
for( var key in js[i]) {
if(js[i].hasOwnProperty(key)) {
var tmpJS= {};
tmpJS['theater'] = key;
tmpJS['time'] = js[i][key];
newJSON.push(tmpJS);
}
}
}

Categories