Iterate through JSON-Object Array - javascript

I parsed a XML file and retrieved the following JSON-object.
The issue is that there are dashes in the json, which causes problems iterating through the object. I can not get rid off them unfortunately.
$(function() {
let json = JSON.parse('{"app-app":{"$":{},"notneeded":"123","mapped":{"$":{},"match-match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"name":"Foo 3","url":"Bar 3"}]},"Nothing":"123"}}');
var foo = Object.keys(json['app-app']['mapped']['match-match']).length;
for (var i = 0; i < foo; i++) {
console.log(json['app-app']['mapped']['match-match'][i].name);
console.log(json['app-app']['mapped']['match-match'][i].url);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I would like to iterate through the object and extract every "match" children. Something like this:
return [
{
name: 'Foo 1',
url: 'Bar 1'
},
[...]
]
Thanks you in advance.

You can simply use Array.prototype.map(), to iterate over your json array and return your custom structure, like this:
$(function() {
let json = JSON.parse('{"app-app":{"$":{},"notneeded":"123","mapped":{"$":{},"match-match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"name":"Foo 3","url":"Bar 3"}]},"Nothing":"123"}}');
var result = json['app-app']['mapped']['match-match'].map(function(item) {
return {
"name": item.name,
"url": item.url
};
});
console.dir(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It will give you the expected result.

let json = JSON.parse('{"app":{"$":{},"notneeded":"123","mapped":{"$":{},"match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"regex":"Foo 3","configuration":"Bar 3"}]},"Nothing":"123"}}');
console.log(json['app']['mapped']['match']);

Related

Extract values from JSON

I have the below JSON string. The id-dashes in the file are not optional unfortunately, neither is the syntax. I would like to extract the "dd" values with JavaScript/Node.
{
"a-id":{
"b-id":"random",
"bb-id":"random",
"bbb-id":"random",
"bbbb-id":{
"c":[
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed_2"
}
]
},
"bbbbb-id":"random",
"bbbbbb-id":"random"
}
}
I would be open to use any additional helper like lodash, jQuery, etc.
The output should be an array with: This_info_is_needed and This_info_is_needed_2.
Thank you in advance.
You can create custom function that will search your data deep and return value if key is dd using for...in loop.
var obj = {"a-id":{"b-id":"random","bb-id":"random","bbb-id":"random","bbbb-id":{"c":[{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"}]},"bbbbb-id":"random","bbbbbb-id":"random"}}
function getDD(data) {
var result = []
for(var i in data) {
if(i == 'dd') result.push(data[i])
if(typeof data[i] == 'object') result.push(...getDD(data[i]))
}
return result
}
console.log(getDD(obj))
If you just interested in the values only, can also just do this:
var obj = {"a-id":{"b-id":"random","bb-id":"random","bbb-id":"random","bbbb-id":{"c":[{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"}]},"bbbbb-id":"random","bbbbbb-id":"random"}};
var desiredResults = obj['a-id']['bbbb-id']['c'].map(function(data){return data.dd});
console.log(desiredResults);

Javascript Key/Value Pairing with Arrays

I am trying to wrap my head around how I might accomplish something like this, structurally:
var keywordDataProducts =
[
{"keyword" : "keyword1", "list" : [ "DP1", "DP2" ] },
{"keyword" : "keyword2", "list" : [ "DP1" ] }
];
But of course, without the values being hard coded. For instance, we currently loop through all the DP values (DP1, DP2, DP3, etc..) - which all have 0-M keywords. I'm trying to create an inverse lookup of that, where you can get all DPs that use a particular keyword. I have code that uses the structure above perfectly, but I just need the data to get populated more dynamically.
Do I initialize the var keywordDataProducts = []; declaration with anything in it, or define the structure of it having a keyword and a list (which is an array)? Or do you leave it as an array with nothing about it, and define that when you're adding items?
I've heard associative arrays can be used for a situation like this, but I'm not quite wrapping my head around that at the moment. I've also seen objects with {} usages, but there is no push there and I need an array of keywords, which also contains arrays of DPs (list). Thoughts?
You would do something like this, but you didn't clearly describe what the input look like and what output you're looking for.
function fn (input) {
var ouput = {};
input.forEach( function (DP) {
for (prop in DP) {
if (DP.hasOwnProperty(prop) {
if (output[prop]) {
output[prop].push(DP);
} else {
output[prop] = [DP];
}
}
}
});
return output;
}
This takes this kind of input
[{"alpha":...}, {"beta":..., "delta":...}, {"alpha":..., "gamma":...}]
and returns
{"alpha":[{"alpha":...}, {"alpha":..., "gamma":...}]}, "beta":{"beta":..., "delta":...}, "delta":{"beta":..., "delta":...}, "gamma":{"alpha":..., "gamma":...}}
I don't know how you want your output so I just made an object with each keyword as its own key for the DP values.
var data = [{dp: "dp1", keys: ["key1", "key2", "key3"]}, {dp: "dp2", keys: ["key1", "key2", "key3"]}, {dp: "dp3", keys: ["key1", "key2", "key3"]},];
function keyWordArray(arr) {
var newObj = {};
arr.forEach((obj) => {
obj.keys.forEach((keyVal) => {
if(newObj.hasOwnProperty(keyVal)){
newObj[keyVal].dp.push(obj.dp);
} else {
newObj[keyVal] = {dp:[obj.dp],};
}
});
});
return newObj;
}
document.getElementById("data").innerHTML = JSON.stringify(keyWordArray(data));
<div id="data">
</div>
You can treat objects as associative arrays, and you don't have to use "push" to add a new element.
// Create your object like this
var keywordDataProducts =
{
"keyword1" : { "list" : [ "DP1", "DP2"] },
"keyword2" : { "list" : [ "DP1" ] }
};
// Treat it like an associative array
var keyword1 = keywordDataProducts["keyword1"];
alert("keyword1 = " + keyword1.list.join(", "));
// Add to it like this
keywordDataProducts["keyword3"] = { "list" : ["DP3", "DP4"] };
// See the new object includes your new keyword
alert(JSON.stringify(keywordDataProducts));
// To iterate the keys of your object, you can do something like this
for(var item in keywordDataProducts)
{
if(keywordDataProducts.hasOwnProperty(item))
{
alert(item);
}
}
You can see the fiddle here;
https://jsfiddle.net/gksjtwr6/2/

loop over array and add separate objects to new array - only one item in new array

I am making a call to a backend API which returns a JSON response. I have read a number of answers on here including this but they dont seem to cover my issue.
The JSON response from the API looks like this:
[
{
"id": "1",
"name": "test1",
},
{
"id": "2",
"name": "test2",
}
]
My Angular JS code looks like this:
controller.testDetailHolder = [];
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder.name = data[i].name;
controller.testDetailHolder.id = data[i].id;
}
});
When I console.log controller.testDetailHolder it only shows the second value from the GET request (i.e. the array just holds one value) however, I want the controller.testDetailHolder to look like this:
controller.testDetailHolder = [
{
id: "1",
name: "test1",
},
{
id: "2",
name: "test2",
}
]
Any assistance with this would be greatly appreciated.
Thanks.
controller.testDetailHolder = [];
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder.push({
name : data[i].hours,
id : data[i].id
});
}
});
Your loop is constantly overwriting controller.testDetailHolder, so you need to use array syntax:
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder[i].name = data[i].hours;
^^^
controller.testDetailHolder[i].id = data[i].id;
}
});
You can assign the data like:
Test.getAllTests.query({}, function(data){
controller.testDetailHolder = data;
});
Or use push to add it to the existing array:
Test.getAllTests.query({}, function(data){
Array.prototype.push.apply(controller.testDetailHolder, data);
});
controller.testDetailHolder is the array itself, not an element within the array. You want to add the values as elements, which is accessed by controller.testDetailHolder[i], where i is the index of the element. Modify your code to be:
controller.testDetailHolder[i].name = data[i].hours;
controller.testDetailHolder[i].id = data[i].id;
The problem is that you are completely overwriting the complete testDetailHolder array, because you do not specify an index when setting the values.
controller.testDetailHolder.name should be controller.testDetailHolder[i].name
Another issue is that you are using data[i].hours when hours is not defined on the JSON.
Lastly since you want to copy the whole object you could just do a single assignment
Test.getAllTests.query({}, function(data){
controller.testDetailHolder = data;
});

How can i send objects as parameter Javascript

I need to pass an array as parameter but i have a problem, i dont know how to explain it so here is the example:
I have this code:
var doc = document;
var Class = {};
Class.Validate = function(opc)
{
alert(opc.id);//
return Class;// when returns the object the alert trigger as expected showing "#name"
};
Class.Validate({
id: "#name",
})
But what im trying to do is this:
var Class = {};
Class.Validate = function(opc)
{
alert(opc.name);//when the object is return show display "carlosmaria"
return Class;//
};
Class.Validar({
name: {field:"carlos",field:"maria"},
})
how can i archived that?
alert(opc.name) should return something like {Object object} because it's an objet. The second point is that your object has twice "field" as property.
If you want to use an array, you should call this way:
Class.Validar({
name: ["carlos", "maria"]
})
Then, you could loop over opc.name to concatenate a full name. Something like this:
Class.Validate = function(opc)
{
var name = "";
for (var i=0, len=opc.name.length; i<len; ++i) {
name += opc.name[i];
}
alert(name);//when the object is return show display "carlosmaria"
return Class;//
};
Consider using actual arrays (via array literals):
Class.Validate({
name: ["carlos", "maria"]
});

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");

Categories