How can I use jQuery to push JSON data into an array? - javascript

I'm new to jQuery, and I'm trying out the getJSON function. What I want to do is pull the "id" section of a JSON file and push it into an array called planes in jQuery. From there, the array is used in an autocomplete function to fill in the searchable IDs.
var planes = [];
$.getJSON('planes.json', function(data) {
console.log('Filling array...');
//This is where I think the issue is occurring.
//Is using the name of the section you want to use the correct syntax here?
$.each(data.id, function (index, val) {
planes.push(val.id);
console.log('Pushed ' + index);
});
});
// After getJSON, array should look something like this:
// var planes = [
// 'Alara',
// 'Fiora',
// 'Innistrad',
// 'Kamigawa',
// 'Lorwyn',
// 'Mirrodin',
// 'Ravnica',
// 'Shandalar',
// 'Zendikar'
// ];
The JSON file is arranged like so:
[
{"id": "Ravnica"},
{"id": "Lorwyn"},
{"id": "Innistrad"},
{"id": "Zendikar"},
{"id": "Kamigawa"},
{"id": "Mirrodin"},
{"id": "Shandalar"},
{"id": "Alara"},
{"id": "Fiora"}
]
Plunker
Any help is much appreciated.

You almost have it, although you are looping through data.id which is not what you want to be doing. You should just loop through data, and push val.id.
If you wanted to loop through data.id, then you're json would have to be structured like so:
{
"id": [
"things",
"to",
"loop",
"through"
]
}
..but it's not, so just loop through data.

Please check following solution. I have hard coded plane data instead of getting from file but solution is same. You just need update your $.each line by iterating over data instead of data.id (this is you'r bug rest of code is fine).
var data = [{
"id": "Ravnica"
}, {
"id": "Lorwyn"
}, {
"id": "Innistrad"
}, {
"id": "Zendikar"
}, {
"id": "Kamigawa"
}, {
"id": "Mirrodin"
}, {
"id": "Shandalar"
}, {
"id": "Alara"
}, {
"id": "Fiora"
}];
var planes = [];
//surround this each with your $.getJSON. I have just hardcoded json data instead of getting it from file
$.each(data, function(index, val) {
planes.push(val.id);
});
console.log(planes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your update plunker link Plunker

You might also look into the native array map method, which saves you having to create an array and then push things onto it. It just returns a new array given the original array by applying the mapping function on each item.
$.getJSON("planes.json",function(data){
console.log(data.map(function(plane){return plane.id;}))
}
However, this is not available in IE<=8 if I recall correctly.

Related

Create nested JSON array

I'm trying to create a JSON array to send it to my web service. This is how my json should look like:
[{
"tipus": 1,
"proveidor": 3,
"atributs": {
"atribut":{
"id": 1,
"valor": 8
},
"atribut":{
"id": 2,
"valor": 500
}
}
}]
So, I have two general values "tipus" and "proveidor" and multiple "atributs" each "atribut" is composed with "id" and "valor".
When I construct the json I get this instead of what I want:
[
2:{
"tipus": 1,
"proveidor": 3,
1:{
"id": 1,
"valor": 8
},
0:{
"id": 2,
"valor": 500
}
}]
This is how I'm building the json:
// For every founded in $scope.atrb i need to create an 'atribut' element into my json
$scope.a = [];
var key;
for(key in $scope.atrb){
var newField = {
"idatributs_actiu": $scope.atrb[key].idatributs_actiu,
"nomAtribut": $scope.atrb[key].nomAtribut,
"valor": $scope.atrb[key].valor,
"idActiu": $routeParams.idTipusActiu,
"value": "",
"ordre": $scope.atrb[key].ordre,
"idatributs_generics": $scope.atrb[key].idatributs_generics
};
$scope.a.push(newField);
}
$scope.f = $scope.a;
});
var generics = {
"nom": $scope.nom,
"tipus": $routeParams.idTipusActiu,
"proveidor": $scope.proveidor.id
};
$scope.a.push(generics);
It's my first project with angular and I'm not sure if I'm building the json appropriately, basically i use an array to build a json but I don't know how to nested it 'atribut' inside 'atributs'.
The main idea is to read the 'generics' atributes and then loop through 'atributs' and read all 'atribut' element getting the properties.
Regards
Like S4beR and Kevin B told me, I just need to do an JS array. This is in my controller:
var obj = { generics: g, atributs: $scope.a };
g: it's an object with the generic properties
$scope.a: this is an array with 'atribut' objects which contais all
the properties I need save to.

How to find JSON object contains Object or Array in Javascript?

I am working Angular js project, I am getting form server response is JSON Object. That JSON Object contains nested Objects and Arrays. for every time i need write lot coding getting the value of key
Ex:
{
"mapData": {
"data": [
{
"key": "name",
"value": "abc"
},
{
"key": "name",
"value": "bcd"
},
{
"key": "name",
"value": "vbc"
}
]
}
}
what i was tried example is so many times, it is not related above example.
for(var key in object) {
if(key=="Id"){
Id= object[key].fieldValue;
secondData.forEach(function(item){
for(var innerItem in item){
if(innerItem =="Id"){
if(Id==item[innerItem].fieldValue){
FinalData.push(item);
}
}
}
});
}
}
Is there any way generic way Instead of writing every time for for loop and For Each loop.
could you please suggest any things
Thanks in advance
mapData.data[i].key will return your key value. i is index of your data array you can easily iterate data by
for(var i =0;i<mapData.data.length;i++){}

make sure values in array are unique when pushing

I push in values from JSON into a several arrays using Underscore, but I want to eliminate any repeated values if there are any, either during push or after. How could I do this?
JSON
looks = [{
"id": "look1",
"products": ["hbeu50271385", "hbeu50274296", "hbeu50272359", "hbeu50272802"]
}, {
"id": "look2",
"products": [
"hbeu50274106", "hbeu50273647", "hbeu50274754", "hbeu50274063", "hbeu50274911", "hbeu50274106", "hbeu50240022", "hbeu50271944"
]
}, {
"id": "look3",
"products": [
"hbeu50272935", "hbeu50274426", "hbeu50271624", "hbeu50274762", "hbeu50275366", "hbeu50274433", "hbeu50262002", "hbeu50272364", "hbeu50272359"
]
}
.......
]
JS (Underscore)
var productArrays = [];
_.each(looks, function(look) {
var productArray = [];
_.each(look.products, function(product) {
productArray.push(product.replace(/_.*/, ''))
})
productArrays.push(productArray);
});
There are couple ways
1.Use _.uniq
_.uniq(productArray);
2.Use _.indexOf before push to productArray
Example
For array's content be unique, how about using _.uniq?
Or just check existence of value before really push it.
function uniquePush(arr, valueToPush) {
if(arr.indexOf(valueToPush) == -1) {
arr.push(valueToPush)
}
}

How to parse through a JSON object Map

If I have a JSON Object Map :
var dataItem=[{
"Lucy":{
"id": 456,
"full_name": "GOOBER, ANGELA",
"user_id": "2733245678",
"stin": "2733212346"
},
"Myra":{
"id": 123,
"full_name": "BOB, STEVE",
"user_id": "abc213",
"stin": "9040923411"
}
}]
I want to iterate through this list and access the names (i.e. Lucy, Myra ) and corresponding information
All the loops that I came across looped through the list like this :
var dataItem = [
{"Name":"Nthal","Class":3,"SubjectName":"English "},
{"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
{"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
{"Name":"Michal","Class":5,"SubjectName":"Gk"},
]
for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}
Thanks in advance
What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:
var data = dataItem[0];
for(name in data) {
alert(name);
alert(data[name].id);
alert(data[name].full_name);
}
for (var x in dataItem[0]) {
if (dataItem[0].hasOwnProperty(x)) {
console.log(x);
}
}
http://jsfiddle.net/B44LW/
If you want other properties, then you can use the bracket notation:
dataItem[0][x].id

Parse JSON with jQuery

I am trying to parse the following JSON with jQuery and get each id value. Can anyone advise?
[
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
]
So far I have:
$.each(test, function(i,item){
alert(item);
});
But that simply lists every value. How can I
That'll list every object in your array, to get the id property of the one you're on, just add .id like this:
$.each(test, function(i,item){
alert(item.id);
});
If test is a string containing JSON, you can parse it with jQuery.parseJSON, which will return a JavaScript object.
If test is written like this:
var test = [
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
];
...it already is a JavaScript object; specifically an array. jQuery.each will loop through each array entry. If you want to loop through the properties of those entries as well, you can use a second loop:
$.each(test, function(outerKey, outerValue) {
// At this level, outerKey is the key (index, mostly) in the
// outer array, so 0 or 1 in your case. outerValue is the
// object assigned to that array entry.
$.each(outerValue, function(innerKey, innerValue) {
// At this level, innerKey is the property name in the object,
// and innerValue is the property's value
});
});
Live example

Categories