can't address JSON object - javascript

I have a locally saved JSON file in which I have a bunch of objects/strings. I have trouble addressing each value. The beginning looks like this:
{
"result":{
"heroes":[
{
"name":"npc_dota_hero_antimage",
"id":1,
"localized_name":"Anti-Mage"
},
{
"name":"npc_dota_hero_axe",
"id":2,
"localized_name":"Axe"
},
...
after including it in my JS I attempt to console log console.log(heroes.result[0].heroes[0].name).
I know it's a dumb question but I can't figure it out right now.This is my markup:
const endpoint = './heroes.json'
let heroes = []
fetch(endpoint)
.then(blob => blob.json())
.then(data => heroes.push(data))
console.log(heroes)

Result is an object and not an array. You need to remove the index from that
heroes.result.heroes[0].name
var heroes={
"result":{
"heroes":[
{
"name":"npc_dota_hero_antimage",
"id":1,
"localized_name":"Anti-Mage"
},
{
"name":"npc_dota_hero_axe",
"id":2,
"localized_name":"Axe"
}]
}
}
console.log(heroes.result.heroes[0].name)

You need to use . for object properties as result is object you need to use . instead of []
var heroes={
"result":{
"heroes":[
{
"name":"npc_dota_hero_antimage",
"id":1,
"localized_name":"Anti-Mage"
},
{
"name":"npc_dota_hero_axe",
"id":2,
"localized_name":"Axe"
}]
}
}
console.log(heroes.result.heroes[0].name)

`heroes.result.heroes[0].name`
That should do. Bear in mind that result is a property of the first object 'heroes' as well as the second 'heroes' is a property of the object 'result'.
The key of the second 'heroes', however, is an array. Therefore you use an index to access the first element in the array: heroes[0].
Third, heroes[0] contains an object so we are accessing its property 'name', therefore .name.

Related

Access and extract values from doubly nested array of objects in JavaScript

I have an array of objects and within those objects is another object which contains a particular property which I want to get the value from and store in a separate array.
How do I access and store the value from the name property from the data structure below:
pokemon:Object
abilities:Array[2]
0:Object
ability:Object
name:"blaze"
1:Object
ability:Object
name:"solar-power"
How would I return and display the values in the name property as a nice string like
blaze, solar-power ?
I tried doing something like this but I still get an array and I don't want to do a 3rd loop since that is not performant.
let pokemonAbilities = [];
let test = pokemon.abilities.map((poke) =>
Object.fromEntries(
Object.entries(poke).map(([a, b]) => [a, Object.values(b)[0]])
)
);
test.map((t) => pokemonAbilities.push(t.ability));
Sample Data:
"pokemon": {
"abilities": [
{
"ability": {
"name": "friend-guard",
"url": "https://pokeapi.co/api/v2/ability/132/"
},
"ability": {
"name": "Solar-flare",
"url": "https://pokeapi.co/api/v2/ability/132/"
}
}
]
}
Then I am doing a join on the returned array from above to get a formatted string.
It just seems like the multiple map() loops can be optimized but I am unsure how to make it more efficient.
Thank you.
There is no need for a loop within loop. Try this:
const pokemon = {
abilities: [{
ability: {
name: 'friend-guard',
url: 'https://pokeapi.co/api/v2/ability/132/'
},
}, {
ability: {
name: 'Solar-flare',
url: 'https://pokeapi.co/api/v2/ability/132/'
}
}]
};
const pokemonAbilities = pokemon.abilities.map(item => item.ability.name).join(', ');
console.log(pokemonAbilities);

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Modify an array of objects inside an array of objects in js

Hello developers I'm trying to modify an array of objects inside an array of objects before deploying its result to Redux reducer.
The array is obtained through a request to an endpoint, reason why i must to create an instance of writable copy of it , and then proceed on the process
Lest say i have this array:
allProducts= [
{
"product_type": "Bikes",
"product_imgs": [
{
"id": 5,
"url": "Mountain Bike/Screenshot (200)"
},
{
"id": 6,
"url": "Mountain Bike/Screenshot (200)"
}
],
"product_name": "product test 1"
},
{
"product_type": "Bikes",
"product_imgs": [
{
"id": 7,
"url": "City Bike/banderaa"
},
{
"id": 8,
"url": "City Bike/banderaa"
}
],
"product_name": "product test 2"
}
]
I would like to modify the items inside the array product_imgs of each object , but for that , having in mind this array comes from a request , i do create a readable copy an over that i set the logic.
let instance=[...allProducts];
then using a double for each (though i also tried using a doule for loop) i reach till every image inside the array of objects product_imgs of each object :
instance.forEach(array=>array.product_imgs.map(element => {
this.imgDownLoaderFirebase
.ref(element.url)
.getDownloadURL()
.toPromise()
.then((url) => {
console.log(url);
//then in this space once the url of some firebase endpoint is reached and else
//i would like to modify that object inside the array product_imgs which is at the same time
//part of the instance array.
//For that i expose that this new url gotten would be asigned as the new
//value thus
element = { ...element };
element.url=url
console.log(element);
console.log(instance);//Printing the general array in order to check if changes committed
})
})
I want to specify that i use first a foreach and then a map in order to modify the inner array of objects result , but using a double for each doesn't precisely inmprove this situation:
instance.forEach(array=>array.product_imgs.forEach(element => {........
Then checking the logs , the element (item url) inside the array of objects product_imgs of the array of obejcts instance , is modified , but the external array containing the inner modified not
How could i improve this?
Thanks
If your goal is to extract all product_img values from your array, you could try something like the following :
// This line will convert your array of object into an array of array of urls, using a destructuring process
const urls = allProducts.map(({ product_img }) => product_img);
// This line will merge the previous result into a single-level array of urls that you can iterate onto.
const result = [].concat([], ...res);
Edit : I forgot to mention that this process will in fact return an array of objects including your id and url.

Node js defining response payload structure

I am having a data coming from elastic search with hits object through node server . I want to send back to the user by transforming it into a payload structure object . For example ,
{
"title":"test",
"count":36
"description":"something for test"
},
{...}
]```
Then from this array I want only title to be sent to user . How can I transform in node js as an object by defining a model
Transform Structure :
```{ "pageNo":1,
"payload":
[
{"title":"test"}
,{...},
{...}
] }```
You are dealing with array so you need to iterate over it. Best approach in that case is to use map method:
const array = [
{
"title":"test",
"count":36,
"description":"something for test",
},
];
const responseItems = array.map(item => {
return { title: item.title };
});
const response = {
payload: responseItems,
// other fields...
};

How do I access certain info from a JSON data file? is it through array form? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
In the following JSON data, I want to access 'lon' and 'lat' in 'coord'. I know data.coord would give me [ 'lon', 'lat' ], but how can I get the values belonging to each?
Here's my JSON data:
var data = {
"coord": {
"lon": 159,
"lat": 35
},
...
};
You could accesss them like this:
var data = { "coord":{ "lon":159, "lat":35 }, "weather":[ { "id":500, "main":"Rain", "description":"light rain", "icon":"https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F10n.png?1499366021399" } ], "base":"stations", "main":{ "temp":22.59, "pressure":1027.45, "humidity":100, "temp_min":22.59, "temp_max":22.59, "sea_level":1027.47, "grnd_level":1027.45 }, "wind":{ "speed":8.12, "deg":246.503 }, "rain":{ "3h":0.45 }, "clouds":{ "all":92 }, "dt":1499521932, "sys":{ "message":0.0034, "sunrise":1499451436, "sunset":1499503246 }, "id":0, "name":"", "cod":200 };
console.log('Lon',data.coord.lon);
console.log('Lat',data.coord.lat);
//Also you can do that using object destructuring in es6 like this:
var {lon,lat} = data.coord;
console.log('Lon',lon);
console.log('Lat',lat);
Checkout MDN for more about objects and properties:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Check out Object destructuring
data.coord won't give you [ 'lon', 'lat' ] array, rather it would give you { "lon": 159,"lat": 35 } object.
You can get their values just like you would get value of any object like: data.coord.lat and data.coord.lon
So something like
var latitude = data.coord.lat;
var longitude = data.coord.lon
EDIT:
Similarly, for weather you can access weather using data.weather, however thing to note is that weather is an array. So, you can get hold of 1st element using index=0.
Effectively, you'll write, var myWeatherObject = data.weather[0]; //0 is index of 1st element
Again, to access individual weather properties, you can use:
myWeatherObject.id, myWeatherObject.main, myWeatherObject.description and myWeatherObject.icon
You can also access the values with this syntax data['coord'].
With this syntax you can run through the json file searching for a corresponding key.
for(let key in json) {
if(key==='coord'){
//do stuff
}
}

Categories

Resources