JavaScript making an array of key value object from a string - javascript

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.

Related

Creating multiple arrays of objects

For an experiment I'm writing, I have to make six of the kind of list below.
var list1 = [];
var enc_len_1 = pregenerated_faces[1].encoding_faces.length;
var rec_len_1 = pregenerated_faces[1].recall_faces.length;
for (var i = 0; i < enc_len_1; i++){
var obj_encode = {
'encode': pregenerated_faces[1].encoding_faces[i]
};
list1.push(obj_encode);
};
for (var i = 0; i < rec_len_1; i++){
var obj_recall = {
'reacall': pregenerated_faces[1].recall_faces[i]
};
list1.push(obj_recall);
};
Each list will look like this:
list = [{encode: ...jpg}, {encode: ...jpg}..., {recall: ...jpg}, {recall:...jpg}...]
What is a smarter way to make six of these without writing six-fold redundant code?
Oh, also, pregenerated_faces is an array of .json objects containing all the encoding and recall faces image strings.
var lists = [];
for (var face of pregenerated_faces) { //should loop 6 time
var list = [];
face .encoding_faces.forEach( e => list.push({'encode': e}));
face .recall_faces.forEach( e => list.push({'recall': e}));
list.push(list);
}
Check this, I have created a function that will give you N lists depending upon the input size of your pregenerated_faces, and your list renderer is also out of the implementation so that it can be used anywhere... and can be changed too
function getNObjects(N, keyCallback) {
const output = []
for (var i = 0; i < N; i++) {
output.push(keyCallback(i));
}
return output
}
// your code
function createList(index) {
var list = [];
var enc_len = pregenerated_faces[index].encoding_faces.length;
var rec_len = pregenerated_faces[index].recall_faces.length;
for (var i = 0; i < enc_len; i++) {
var obj_encode = {
'encode': pregenerated_faces[index].encoding_faces[i]
};
list.push(obj_encode);
};
for (var i = 0; i < rec_len; i++) {
var obj_recall = {
'reacall': pregenerated_faces[index].recall_faces[i]
};
list.push(obj_recall);
};
return list
}
// Test case
const pregenerated_faces = [{
name: "Ardis Pool",
gender: "male"
},
{
name: "Barbra Panganiban",
gender: "female"
},
{
name: "Ralph Sales",
gender: "male"
},
]
// Test Function
function testFunction(index) {
var list = [];
var enc_len = pregenerated_faces[index].name
var rec_len = pregenerated_faces[index].gender
var obj_encode = {
'encode': enc_len
};
list.push(obj_encode);
obj_recall = {
'reacall': rec_len
};
list.push(obj_recall);
return list
}
const [one, two, three] = getNObjects(3, testFunction);
console.log(one, two, three)

Push elements of an array to different keys using Javascript & Angular JS

I'm having an array [0,1,2]. I'm trying to assign the array values to an JSON Object as image1:0, image2:1, image3:2, using Javascript but I'm getting confused. Please find my code here
var app = angular.module('app',[]);
app.controller('EventController',function EventController($scope) {
$scope.count = 0;
$scope.next = function() {
var arr = [0,1,2];
var result = {};
for(var i = 0; i < arr.length; i++) {
result.image1 = arr[i];
result.image2 = arr[i];
result.image3 = arr[i];
}
console.log(result)
}
});
My expected result is Object {image1: 0, image2: 1, image3: 2}
But actual result coming is Object {image1: 2, image2: 2, image3: 2}
My fiddle http://jsfiddle.net/Zvy2c/67/
You may use the bracket operator for accessing the property
for (var i = 0; i < arr.length; i++) {
result['image' + (i + 1)] = arr[i];
}
You are looping through arr and assigning the same value to all your properties. You set everything to 0, then 1, then 2.
Forget about the for loop and just set the properties to whichever entry in the array you want:
var arr = [0,1,2];
var result = {
image1: arr[0],
image2: arr[1],
image3: arr[2]
};
var app = angular.module('app',[]);
app.controller('EventController',function EventController($scope) {
$scope.count = 0;
$scope.next = function() {
var arr = [0,1,2];
var result = {};
for(var i = 0; i < arr.length; i++) {
result['image' + (i+1)] = arr[i];
}
console.log(result)
}
});
You need to change your for loop as
for(var i = 0; i < arr.length; i++) {
result['image'+i] = arr[i];
}

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 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

converting array of array into array of keyvalue pairs

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.

Categories