I am new to node and I am trying to fetch name from the obj but the problem is
How to fetch data from inner json object as my json object look like this
let obj=
{
"h4354desdfqw":{
name:"Computer",
os:"Window",
},
"hjsado24334":{
name:"Software",
type:"Adobe",
},
"qwsak032142":{
name:"hardware",
type:"hardisk",
},
}
console.log(obj.h4354desdfqw.name)
I am trying to fetch all the name which are present inside the json object
like this
computer
Software
hardware
I am not sure in which representation you would like get the data. I can assume - you would like to get array of the names
let obj=
{
"h4354desdfqw":{
name:"Computer",
os:"Window",
},
"hjsado24334":{
name:"Software",
type:"Adobe",
},
"qwsak032142":{
name:"hardware",
type:"hardisk",
},
}
const result = Object.values(obj).map(i => i.name);
console.log(result)
Object.values(obj).map(i => console.log(i.name));
You want to get the value of name for each object.
So let's iterate through each object's name with the map function :
const result = Object.values(obj).map(i => i.name);
console.log(result);
Related
I am trying to fetch all the log details from this json object but the problem is this key always get changed
let userJsonObject =
{
"user_1":{
"id":"user_1",
"log":"de-data",
"name":"dummy test",
"address":"New York"
},
"user_2":{
"id":"user_2",
"log":"ex-file",
"name":"tom",
"address":"Nevada"
},
"user_3":{
"id":"user_3",
"log":"dis-acta",
"name":"Jerry",
"address":"LA"
},
}
this is my json Object and I want fetch all the log which are present inside the json object and store them in one array like this
let gotLog= ["de-data","ex-file","dis-acta"]
here user_1 user_2 get changed everytime and I wanted to tackle this scenario and fetch all the log in one array
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]];
I found this here How to access the first property of a Javascript object?
let userJsonObject =
{
"user_1":{
"id":"user_1",
"log":"de-data",
"name":"dummy test",
"address":"New York"
},
"user_2":{
"id":"user_2",
"log":"ex-file",
"name":"tom",
"address":"Nevada"
},
"user_3":{
"id":"user_3",
"log":"dis-acta",
"name":"Jerry",
"address":"LA"
},
};
let array=[];
for(const value of Object.values(userJsonObject)){
array.push(value.log)
};
console.log(array);
I got it :)
I am having a below json array and now I need to iterate over the json object to retrieve two values of fields ServicePort And ServiceAddress and form a final output as {"MyIp" : "http://IP:Port"} from my json array object.
var bodyObject = [
{
"ServiceAddress": "10.X.X.125",
"ServiceConnect": {},
"ServicePort": 80
},
{
"ServiceAddress": "10.X.X.126",
"ServiceConnect": {},
"ServicePort": 80
}
];
I have tried as below to iterate
for (var key in bodyObject ) {
if (bodyObject.hasOwnProperty(key)) {
console.log(bodyObject[key].ServiceAddress);
console.log(bodyObject[key].ServicePort);
}
}
How can I form a output final output like {"MyIp" : "http://IP:Port"} from my json array object each hitting giving me a diffrent Ip's from my above JSON list dynamically. Can someone help on this please
I think you're asking how to create a new array with a single object with a MyIp property whose value is the combination of ServiceAddress and ServicePort. map is the idiomatic way to do that, perhaps with some destructuring to pick out the properties from each object and a template literal to build the resulting string:
const result = bodyObject.map(({ServiceAddress, ServicePort}) => {
return {MyIp: `http://${ServiceAddress}:${ServicePort}`};
});
or with a concise-form arrow function:
const result = bodyObject.map(({ServiceAddress, ServicePort}) =>
({MyIp: `http://${ServiceAddress}:${ServicePort}`})
);
(You need the () around the object literal because otherwise it looks like the full function body form of arrow function to the parser.)
Live Example:
const bodyObject = [
{
"ServiceAddress": "10.X.X.125",
"ServiceConnect": {},
"ServicePort": 80
},
{
"ServiceAddress": "10.X.X.126",
"ServiceConnect": {},
"ServicePort": 80
}
];
const result = bodyObject.map(({ServiceAddress, ServicePort}) =>
({MyIp: `http://${ServiceAddress}:${ServicePort}`})
);
console.log(result);
That has a fair number of newish JavaScript features in it, so just for clarity here's a version without destructuring or a template literal:
const result = bodyObject.map(element => {
return {MyIp: "http://" + element.ServiceAddress + ":" + element.ServicePort};
});
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;
}
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I'm trying to .map through data returned from an API (the NASA API). The issue I'm having is with deeply nested properties -- here's an example.
What's the best way to get the nested name and estimated_diameter properties data in React? All the data's being brought in just fine via axios. Logging out the state returns this:
I'm having trouble map'ing through the data because of the nested objects and arrays.
Assume the nasa data json is saved in the variable nasaData, the code below will print all the name and the estimated_diameter
var nearEarthObjects = nasaData['near_earth_objects'];
for (var property in nearEarthObjects) {
if (nearEarthObjects.hasOwnProperty(property)) {
var data = nearEarthObjects[property];
data.forEach(function(d){
console.log(d['name']);
console.log(d['estimated_diameter']);
});
}
}
ps: this might be for a reactjs project but it's really just javascript
You can map through the dates first.
const { near_earth_objects } = nasaData; //assuming nasaData is the json object
const dateKeys = Object.keys(near_earth_objects);
const nameAndEstimatedDiameters = dateKeys.map((dateKey) => {
const dateData = near_earth_objects[dateKey];
const { name, estimated_diameter } = dateData;
return { name, estimated_diameter };
});
//now nameAndEstimatedDiameters is an array of objects here
//which you can map again