Iterate over json hash in javascript - javascript

Json:
{
"comments":[
{"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"},
{"id":2,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/2.json"},{"id":3,"author_name":"Yerassyl","comment_text":"Hello world!","url":"http://localhost:3000/comments/3.json"},
{"id":4,"author_name":"Yerassyl","comment_text":"hi there","url":"http://localhost:3000/comments/4.json"}
]
}
How to iterate over each comment in comments. I want something like that:
//pseudocode
comments.each(key,value){
// do something
}
I tried map, but map is for arrays.
EDIT:
If i delete root node 'comments' i can use .map:
var commentNodes = this.props.comments.map(function(comment,index){
});
Ignore this.props, it is actually React.js.
console.log(this.props.comments) returns my json objects with root node 'comments'

Assuming you have
var obj = {
"comments":[
{"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"},
{"id":2,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/2.json"},{"id":3,"author_name":"Yerassyl","comment_text":"Hello world!","url":"http://localhost:3000/comments/3.json"},
{"id":4,"author_name":"Yerassyl","comment_text":"hi there","url":"http://localhost:3000/comments/4.json"}
]
};
You can just do, for example,
obj.comments.map(function (comment) {
console.log(comment);
});

Assuming you have already JSON.parsed the string, you can use forEach to iterate. Map is only for returning a new array from your existing values.
this.props.comments.comments.forEach(function(value, index) {
console.log(value, index);
});
edit: Sounds like this.props.comments is the root object. Hence the accessor above

Firstly you have to parse your JSON data:
var json = '{
"comments":[
{"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"},
{"id":2,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/2.json"},{"id":3,"author_name":"Yerassyl","comment_text":"Hello world!","url":"http://localhost:3000/comments/3.json"},
{"id":4,"author_name":"Yerassyl","comment_text":"hi there","url":"http://localhost:3000/comments/4.json"}
]
}';
var data = JSON.parse(json);
And then you can proceed and loop throught comments like this:
data.comments.forEach(function(comment, index) {
console.log("Comments["+index+"]: "+comment);
});
Note:
Once your JSON is parsed you will get an object including an array of comments so you can easily use all the Array.prototype methods with it including forEach and map.

Related

How to get JSON values of multiple keys of the same name

I have a JSON data set as follows:
{
"content":[],
"layout":[],
"trail":[
{
"content":[
{
"type":"image",
"media":[
{
"type":"image/jpg",
"width":593,
"height":900,
"url":"https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg",
"flickr":{
"flickr-post":"https://www.flickr.com/photos/riketrs/48208920877",
"flickr-album":"https://www.flickr.com/photos/riketrs/albums/72157709130951466"
}
}
]
},
{
"type":"image",
"media":[
{
"type":"image/jpg",
"width":1600,
"height":900,
"url":"https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg",
"flickr":{
"flickr-post":"https://www.flickr.com/photos/146758538#N03/33807326532",
"flickr-album":"https://www.flickr.com/photos/146758538#N03/albums/72157681438471236"
}
}
]
}
],
"colors":{
"c0":"#1e1e1d",
"c1":"#78736f",
"c2":"#b2a89f"
}
}
]
}
I would like to console.log the "url" key for each of the images shown here.
(https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg and https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg)
I tried some code but I'm very new to JSON in general, I've looked at some other answers to do with JSON but I'm not quite sure how to achieve what I want.
JSFiddle: https://jsfiddle.net/fj6qveh1/1/
I appreciate all advice, including links to other answers that I potentially missed.
Thank you!
url is a property of an object. There can be many of these in a media array. (This data only shows one object per array.) media itself is an property of objects inside the content array.
Use map, and flatMap.
map to return the URL values from the objects in media, and flatMap to return a flat array of the nested arrays returned by map.
const data={content:[],layout:[],trail:[{content:[{type:"image",media:[{type:"image/jpg",width:593,height:900,url:"https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg",flickr:{"flickr-post":"https://www.flickr.com/photos/riketrs/48208920877","flickr-album":"https://www.flickr.com/photos/riketrs/albums/72157709130951466"}}]},{type:"image",media:[{type:"image/jpg",width:1600,height:900,url:"https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg",flickr:{"flickr-post":"https://www.flickr.com/photos/146758538#N03/33807326532","flickr-album":"https://www.flickr.com/photos/146758538#N03/albums/72157681438471236"}},{type:"image/jpg",width:1600,height:900,url:"https://live.dummyimage.com/2817/dummy.jpg",flickr:{"flickr-post":"https://www.flickr.com/photos/146758538#N03/33807326532","flickr-album":"https://www.flickr.com/photos/146758538#N03/albums/72157681438471236"}}]}],colors:{c0:"#1e1e1d",c1:"#78736f",c2:"#b2a89f"}}]};
const content = data.trail[0].content;
const urls = content.flatMap(obj => {
return obj.media.map(inner => inner.url);
});
console.log(urls)
The easiest way is to use map function. Given that you are very new to programming (the solution has little to do with JSON itself, since the first step is to parse JSON string to a JavaScript object), it would be better if you try yourself. But you start with
let urls = trail["content"].map(x => x["media"][0]["url"])
for more about map function look here
There is a table in the table so for each table:
for(let i in trail){
var content = trail[i]["content"];
content.forEach(content => content.media.forEach(media => console.log(media.url)))
}
To access object properties, you can use a dot (.), and to access an array element, you use its index in square brackets ([]). So you just keep repeating these steps as necessary until you get to the content you're looking for.
Here's how that looks on a simplified version of your object, using the forEach method of arrays to apply a custom function to each item in the content array:
const json = getJson();
json.trail[0].content.forEach(item=>console.log(item.media[0].url));
function getJson(){
let obj = {
"trail": [{
"content": [
{ "media": [{ "url":"image #65535/48208920877_e6b234d3ea_c_d.jpg" }]},
{ "media": [{"url":"image #2817/33807326532_91013ef6b1_h_d.jpg"}]}
]
}]
};
return obj;
}

How to push each object value into array from json?

I have a JSON response with key-values like:
....
"usp-custom-90":"45.45257926613316,9.178168599999935"
....
Note usp-custom-90has dash!
I need something like (fields doens't exist, it's just an example):
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Where coordsB is an array defined before.
The json would be:
],
"usp-custom-90":"45.47841306255037,9.120865849999973",
"_links":{
"self":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts\/128402"
}
],
"collection":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts"
}
],
"about":[
I need to push the value of each "usp-custom-90"
Full code (wrong as it is using fields which doesn't exist):
fetch('https://www.example.it/wp-json/wp/v2/posts?per_page=50&status=publish')
.then(res => res.json())
.then(data =>{
var coordsB = [];
console.log(data);
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Based on the data sample linked in the comments, the structure is an array of objects, each object containing a usp-custom-90 property. This is a perfect situation for the map operator for arrays.
So in the above code, this one line will do it all for you. It will create the array and populate it with all the values you're looking for.
var coordsB = data.map(x=> x["usp-custom-90"])
Something along these lines would do I guess.
Object.entries(object).reduce((ac,[k,v],i,a)=>(ac.push(v['usp-custom-90']),ac),[])
Looks like from your paste bin main object is an array with objects inside which have the key you want then:
YourMainArray.reduce((ac,d,i,a)=>(ac.push(d['usp-custom-90']),ac),[])
Tested it, gives you this:
["45.45257926613316,9.178168599999935", "45.47841306255037,9.120865849999973", "9.924,-84.090", "44.948,9.039", "45.464150416139695,9.1906395499999", "45.651,11.303", "43.83734441524854,7.905822499999999", "45.05926341591318,9.3354875", "44.872988115810074,13.85009094999998", "44.97805886586813,8.895478499999967", "45.472119466144186,9.173527250000006", "45.165,9.183", "41.937,12.441", "45.464993216140186,9.147909499999969", "45.48624411615216,9.16677489999995", "45.209,9.147", "45.464993216140186,9.147909499999969", "41.848264464222716,12.665936949999946", "45.464993216140186,9.147909499999969", "45.46851557705748,9.139416449999999", "44.507,11.314", "36.731,14.873", "36.222,-121.759", "10.093,77.060", "45.454327616134165,9.175796900000023", "45.469282816142574,9.176045000000045"]

How to read the values inside the json array

I have a json like
var obj={
"address":{
"addlin1":"",
"addlin2":""
},
"name":"sam",
"score":[{"maths":"ten",
"science":"two",
"pass":false
}]
}
Now when Iam trying to modify the json iam try an array variable and passing above json to that like
var data=JSON.parse(obj);
var json={};
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];
For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]
So,when i console the json it is in this way
"name":"sam",
"address":{
"addresslin1":"",
"addresslin2":""
},
"score":{}
}
So how can I also read the values inside [] array.
Can someone help me
Thanks
json['maths']=data['score'][0]['maths'];
if you're not sure that data['score'] has any elements you can check prior to reading maths key:
if (data['score'].length) {
json['maths']=data['score'][0]['maths'];
}
data['score'] is an array, so you can't read it like that
json['maths']=data['score']['maths'];
you have to read it like that:
json['maths'] = data['score'][0].maths;
Also, obj is not a JSON, but a JavaScript object. You can use it directly.
json['maths'] = obj['score'][0].maths;
A JSON is a string, like that:
JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";
create another json2 to contain score data then assign to json.
for example :
var json={};
json2 = {}
json2[0] = 1;
json2[1] = 2;
json[0] = json2;

How to dynamically add an attribute to JSON array

I have this JSON array
{"nodes":[
{"type":"simple-node","left":500,"id":"node-start","content":"Start"},
{"type":"simple-node","left":500,"id":"node-1","content":"Ironing"},
{"type":"simple-node","left":500,"id":"node-end""content":"End"}
],
"connections":[
{"start":"node-start","end":"node-1"},
{"start":"node-4","end":"node-5"}
]
}
I need to dynamically add "top" attribute to each element in nodes array so that it may look like this
{"nodes":[
{"type":"simple-node","left":500,"top":3403.252685546875,"id":"node-start","content":"Start"},
{"type":"simple-node","left":500,"top":3703.252685546875,"id":"node-1","content":"Ironing"},
{"type":"simple-node","left":500,"top":3903.252685546875,"id":"node-end""content":"End"}
],
"connections":[
{"start":"node-start","end":"node-1"},
{"start":"node-4","end":"node-5"}
]
You can use forEach on obj.nodes and add object property
var obj = {"nodes":[{"type":"simple-node","left":500,"id":"node-start","content":"Start"},{"type":"simple-node","left":500,"id":"node-1","content":"Ironing"},{"type":"simple-node","left":500,"id":"node-end","content":"End"}],"connections":[{"start":"node-start","end":"node-1"},{"start":"node-4","end":"node-5"}]}
obj.nodes.forEach((e) => {
e.top = 3403.252685546875;
});
console.log(obj)
Update: First you need to turn your json string to object with JSON.parse(yourjson) if you didn't.
var obj={"nodes":[
{"type":"simple-node","left":500,"id":"node-start","content":"Start"},
{"type":"simple-node","left":500,"id":"node-1","content":"Ironing"},
{"type":"simple-node","left":500,"id":"node-end""content":"End"}
]};
var top_array=[2495,4985,3467];
for(i=0;i<obj.nodes.length;i++){
obj.nodes[i].top=top_array[i];
}
In case you need to copy the keys from an array

Javascript: How to parse a json array without knowing the key name?

I want to parse the following json:
{"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
Where key_410441 is the entry's name representing the object's value, and the following array is the object's data.
How can I retrieve it's value?
function defined(json) {
for (var i in json) {
var objId = json[i]. ????
}
}
Like Robo Robok said, use Object.keys(object)
if your json look like {"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
function defined(json) {
var hashId = json[Object.keys(json)[0]].hashId
var tube_id = json[Object.keys(json)[0]].tube_id
}
}
you can use shortcut json[Object.keys(json)] because you have olny one object
key_410441
Object keys are returned in form of an array by Object.keys(object)
I suppose you are using jquery and ajax to get a json from an external file. Then the piece of code would be:-
$.getJSON("aa.json", function(data) {
var obj = Object.keys(data),
json = data[obj];
for(var s in json) {
console.log(json[s]);
}
});

Categories