Iterate json data in javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Following JSON data comes from php,
I have tried following code. But console displays undefined error.
jQuery.each(result.address, function(obj) {
console.log(obj.city);
});
EDIT : Also it's not working and throwing undefined error.
jQuery.each(result.address, function(obj) {
console.log(obj[0].city);
});
It is working : console.log(result.address.address1.city);. But in this case address1 is not fixed. eg. result.address.xyz.city, result.address.abc.city

You're calling city on each address, while cities are inside addressX inside address. Try:
jQuery.each(result.address, function(key, val) {
console.log(val.city);
});
jsfiddle DEMO

Maybe in this way:
for (i = 0; i < result.address.length; i++) {
console.log(result.address[i].city);
}
I'm not sure if jquery.each works in this case.
I hope it helps.

Javascript
var dictionary = {
"12Jan2013": [{
"id": "0",
"name": "ABC"
}, {
"id": "1",
"name": "DEF"
}],
"13Jan2013": [{
"id": "0",
"name": "PQR"
}, {
"id": "1",
"name": "xyz"
}]
};
for (var i in dictionary) {
dictionary[i].forEach(function(elem, index) {
console.log(elem, index);
});
}
Output
Object {id: "0", name: "ABC"} 0
Object {id: "1", name: "DEF"} 1
Object {id: "0", name: "PQR"} 0
Object {id: "1", name: "xyz"} 1

Related

Merge values to an array based on similar object key javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
i have a return like this
[
{
"tripw3": "1"
},
{
"tripw1": "2"
},
{
"tripw1": "3"
},
{
"tripw2": "4"
},
{
"tripw2": "5"
},
{
"tripw3": "6"
},
{
"tripw3": "7"
}]
and I want to make the above result be
[
{
tripw3: ["1", "6", "7"],
tripw2: ["4", "5"],
tripw1: ["3", "2"]
}]
Until now I'm still confused to make this happen.
You cane easily acheve the result using reduce, Object.keys and forEach
const arr = [
{
tripw4: "1",
},
{
tripw4: "2",
},
{
tripw4: "3",
},
{
tripw4: "4",
},
{
tripw4: "5",
},
{
tripw4: "6",
},
{
tripw4: "7",
},
];
const result = [arr.reduce((acc, curr) => {
Object.keys(curr).forEach((k) => acc[k] ? acc[k].push(curr[k]) : (acc[k] = [curr[k]]));
return acc;
}, {})];
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

I need help converting this array of objects into an array of arrays [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following array of objects:
[
{
"messages": {
"m1": {
"message": "Relay malfunction found. Cause: moth.",
"sender": "ghopper"
}
},
"title": "Historical Tech Pioneers",
"key": "one"
} ]
But I wish to convert it to an array of arrays. For example: I want to turn the title field below:
"title": "Historical Tech Pioneers"
Into:
"title": [ "Historical Tech Pioneers" ]
Thank you for your help
Assuming the declaration:
var myArr = [
{
"messages": {
"m1": {
"message": "Relay malfunction found. Cause: moth.",
"sender": "ghopper"
}
},
"title": "Historical Tech Pioneers",
"key": "one"
}
];
You can iterate over each element and reassign the property using:
myArr.forEach(o => o.title = [o.title]);
Or without ES6:
myArr.forEach(function (o) {
o.title = [o.title]);
});

Find specific key/value in array of objects and print out another key/value in that object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have this response from a $.getJSON call. Now I want to select the name property of the object with "selected": true, and print it to a div with id charTitle.
"titles": [{
"id": 17,
"name": "Sergeant %s"
}, {
"id": 53,
"name": "%s, Champion of the Naaru"
}, {
"id": 64,
"name": "%s, Hand of A'dal",
"selected": true
}]
You can achieve this with a simple loop:
for (var i = 0; i < obj.titles.length; i++) {
if (obj.titles[i].selected) {
$('#charTitle').text(obj.titles[i].name);
}
}
Example fiddle
Or with jQuery's $.each():
$.each(obj.titles, function(i, title) {
if (title.selected)
$('#charTitle').text(title.name);
});
Note that if you have multiple objects in the array with selected set to true you would need to use append() instead of text() to set the content of the div, otherwise the previous value will be overwritten.
using underscore you can get this with
var titles = ...
_.findWhere(titles, {selected: true});
see http://underscorejs.org/#findWhere
Try using Array.prototype.filter()
var arr = [{
"id": 17,
"name": "Sergeant %s"
}, {
"id": 53,
"name": "%s, Champion of the Naaru"
}, {
"id": 64,
"name": "%s, Hand of A'dal",
"selected": true
}]
var res = arr.filter(function(val, key) {
return val.selected === true
})[0].name;
$("#charTitle").html(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="charTitle"></div>

Display multiple same JSON keys using Angularjs [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
When I type Monday and click Search I want to get all of Monday's JSON data and not just the first row. I've tried modifying the forEach function and also using two ng-repeats in html. So I guess it's the JSON Data structure?
Fiddle.
"Monday": [{
"Name": "John",
"Address": "Street",
"Phone": "111",
"Status": "Sleep"
},
{
"Name": "Sam",
"Address": "Street2",
"Phone": "2",
"Status": "Awake"
}
],
"Tuesday": [{..............................
You need to use this code:
angular.forEach($scope.items, function (value, key) {
if (key === enteredValue) {
angular.forEach(value, function(item) {
$scope.results.push({
name: key,
address: item.Address,
phone: item.Phone,
status: item.Status
});
});
}
});
The problem was that you only used one forEach, when you actually need two. Not a problem with your data structure.
You could also just do this, however:
angular.forEach($scope.items[enteredValue], function (item, key) {
$scope.results.push({
name: enteredValue,
address: item.Address,
phone: item.Phone,
status: item.Status
});
});
which would be must simpler. I hope this helps!

call javascript object properties [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is probably a very easy question but let's say I have a php json_encoded javascript object of this form:
var js_objet = {
"1": {
"Users": {
"id": "14",
"name": "Peter"
},
"Children": [
{
id: 17,
name: "Paul"
},
{
id: 18,
name: "Mathew"
}
]
}
}
What is the synthax to get the name of the child with id 18 (Mathew) for example from that Object?
Thank you
Here's such a custom function as mentioned earlier.
function getChildrenById(id){
for (var child in js_objet[1].Children){
if(id == js_objet[1].Children[child].id){
return js_objet[1].Children[child].name;
}
}
return false;
}
running getChildrenById(18) would return "Mathew"
Hope that helps,
R.
You can do it like this:
var name = js_objet["1"].Children[1].name;
JSFiddle available here
This is how I would approach this problem:
var id = 18;
var name = '';
var jsObjIndex = "1";
var jsObjAttr = "Children"
for (var i = 0; i < js_objet[jsObjIndex][jsObjAttr].length; i++)
{
if (js_objet[jsObjIndex][jsObjAttr][i].id == id)
{
name = js_objet[jsObjIndex][jsObjAttr][i].name;
break;
}
}
You are basically performing a linear search on every element of jsObjIndex.Children. There are likely better solutions however :).
This really is a comment, but I don't have enough reputation (but it's relevant as I recently encountered the same issue): This would probably be easier to do if you can change the JSON format to use the ID as the key for each child object:
var js_objet = {
"1": {
"Users": {
"id": "14",
"name": "Peter"
},
"Children": {
"17":{
"name": "Paul"
},
"18":{
"name": "Mathew"
}
}
}
}
Then you can simply call it using
js_objet[1].Children[18].name;
This is assuming each ID is unique.

Categories