Parsing JSON to a regular JavaScript array - javascript

How can I load a regular array from a JSON Response like this:
{"project":"8","powerline":"188.396496","road":"7.876766","cost":"69885005.45"}
to
var cars = [8, 188.396496, 7.876766, 69885005.45];
I already tried something like this:
req.done(function(data) {
var cars = JSON.parse(data);
});
but it is not doing the job.

You can simply run a for..in loop like this. and keep pushing the values into a new array.
var obj = {
"project" : "8",
"powerline" : "188.396496",
"road" : "7.876766",
"cost" : "69885005.45"
}
var arr = [];
for (var key in obj) {
var val = parseFloat("0" + obj[key]);
arr.push(val)
}

You can manipulate JSON object as Array, please try this way
req.done(function(data) {
var cars = $.map(JSON.parse(data), function(value, index){
return i;
});
console.log(cars);
});

That's because you're getting an object when you're calling JSON.parse. You can run the following to get the values without keys:
req.done(function (data) {
var jsonData = JSON.parse(data),
cars = []
for (var key in jsonData) {
cars.push(jsonData[key])
}
})

Related

Cannot form keyvalue pair in javascript in desired format

I have formed a keyvalue pair in JavaScript using the below code:
for(i=1;i<=results.totpage;i++)
{
pushToAry(i,i);
}
Assume results.totpage as 300.
The method pushToAry():
function pushToAry(name, val) {
//alert("In the array");
var obj = {};
obj[name] = val;
ary.push(obj);
}
where ary is defined as var ary = [];
Using the above format the result that comes out is like:
But I want to make it like [["key1", "value1"],["key2", "value2"],["key3", "value3"]] i.e. to replace the 2nd brackets with the 3rd brackets.
Please help.
Instead of pushing a object to ary, push a new array:
var ary = [];
function pushToAry(name, val) {
//alert("In the array");
var arr = [name, val];
ary.push(arr);
}

Javascript object in array

Lets say I have a object like
> var products = {a:"b", c:"d", e:"f" ... it goes like this}
i want to put this object in array like this
> var arrList = [[a,b],[c,d],[e,f]]
but i couldnt managed it'll be great if you guys help me thank you already
Just loop and add it to the array
var result = []
for (var key in products) { result.push([key,products[key]]) }
One possible approach:
var arrList = Object.keys(products).map(function(key) {
return [key, products[key]];
});
Note, though, that properties order in objects are not guaranteed in JavaScript.
You can proceed like this:
var products = {a:"b", c:"d", e:"f"};
var arrList = [];
for(var key in products) { // iterates over products key (e.g: a,c,e)
arrList.push([key, products[key]]);
};
Use for-in loop to iterate through object
for (variable in object) => variable is a property name
Try this:
var products = {
a: "b",
c: "d",
e: "f"
};
var arr = [];
for (i in products) {
arr.push([i, products[i]]);
}
snippet.log(JSON.stringify(arr));
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it as follow
products = {a:"b",c:"d",e:"f"};
arrList = [];
for(i in products){
arrList.push([i,products[i]]);
}

How to convert a array containing object string to regular key object pair?

I am trying to convert my uri to object value, as a success level i converted and splited in to array values with colon. But i am not able to onvert those to regular object. any one suggest me a good way. I am suing underscorejs with me.
here is my code :
var ar = ["id:1231", "currency:GBP"];
var outPut = _.map(ar, function(item){
return '{' + item + '}';
})
console.log(outPut); //consoles as ["{id:1231}", "{currency:GBP}"]
how can i get result like this:
var object = {id:1231, currency:GBP}
is underscore has any in build method for this?
There are several ways you could go about this, and Underscore offers helpers for them.
One way would be to use _.reduce to incrementally add key/value pairs to an initially empty "result" object:
var obj = _.reduce(ar, function(result, item) {
var keyAndValue = item.split(":");
result[keyAndValue[0]] = keyAndValue[1];
return result;
}, {});
Note that you can do the same without Underscore unless you have to support IE 8 or earlier.
Without any third part library:
var output = {} ;
var ar = ["id:1231", "currency:GBP"];
ar.forEach(function (item) {
var values = item.split(':') ;
output[values[0]] = values[1] ;
}) ;
Output console.log(output):
Object {id: "1231", currency: "GBP"}
Here is another version using jQuery:
var newObj = {};
$.each( ar, function( i, v ) {
var kv = v.split( ":" );
newObj[ kv[0] ] = kv[ 1 ];
});
// newObj = {id:"1231", currency:"GBP"}

Retrieve Value Using Key in Associative Array

I have an array into which I insert a load of values along with their corresponding keys. They are inserted fine as I can see them all in the array when I do a console.log.
The issue is, I can't seem to retrieve the values from the array using their respective keys.
Here is my code.
var personArray = [];
personArray.push({
key: person.id,
value:person
});
var personID = person.id;
console.log(personArray.personID);
I have also tried console.log(personArray[personID]; but this does not work either.
The value I get in my console is undefined.
What you are doing is that you push dictionaries into the array. If person.id is unique, then you can do this:
var personDict = {}
personDict[person.id] = person
and then personDict[personID] will work. If you want to keep your structure, then you have to search inside the array for it:
var personArray = [];
personArray.push({
key: person.id,
value:person
});
var personID = person.id;
var search = function(id) {
var l = personArray.length;
for (var i = 0; i < l; i++) {
var p = personArray[i];
if (p.key === id) {
return p.value;
}
}
return null;
};
search(personID);
You can use dictionary format as suggested by #freakish,
Or use the filter function to find the required object.
For example:
var personArray = [];
var person = {id: 'aki', value:'Akhil'}
personArray.push({
key: person.id,
value:person
});
personArray.filter(function(item){
return item.key == 'aki'
});

How to dynamically create a ARRAY based on a AJAX response?

How do I dynamically create a array after getting a AJAX response ?
The variable data.villages is my response.
I loop over its value using the jQuery each function:
$.each(data.villages, function(key, value) {
//Here I have the 2 variables: value.id and value.name
//Now I need to build a array where the value.id is the KEY and the content is name : value.name
//After I need to create an array with all the arrays
});
My final array should look like this:
[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]
I need this to get the name value (or any other property) by knowing the ID....
Can you also show me example on how to get this data by knowing the ID ?
To create an array of objects from your json response you should be able to do something like this:
var arrayOfObjects = [];
for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
arrayOfObjects.push(data.villages[i]);
}
What I think you actually want is an object. You can object like so:
var objectFromJson= {};
for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
var currentItem = data.villages[i];
objectFromJson[currentItem.WhatEverPropertyYouWantForTheKey] = currentItem;
}
I think your final array is wrong:
[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]
must be:
[
{ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] }
]
that is, an array with an object with the id=234141 and value [{name: ....}]
You can achieve that with:
data.villages = "your returned data array";
var newArray = [ { 234141: [] } ];
$.each(data.villages, function(key, value) {
newArray[0]['234141'].push({key: value};
}
you could try something like
arr = new Array();
arr[value.key] = {var1: 'vila1', var2: 'vila2'};
you are just storing json

Categories

Resources