JavaScript, access json property - javascript

I have a .json file like this:
import single from 'file.json'
{
"id": 4,
"code": 4508099576,
"important": [
{
"id": 4,
"name": "services"
}
]
}
I want to access "services" for render it. But the following syntax doesn´t work:
<span>Plans: {single.important.name}</span>

important is an array and you need to access its first object. Your would write
<span>Plans: {single.important[0].name}</span>
In case if you want to render all the plans within the important array, you would make use of map like
<div>{single.important.map((obj) => {
return <span key={obj.id}>Plans: {obj.name}</span>
})</div>

Important is an array. You need to access it with an index ex.
single.important[0].name

Related

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.

React-Admin: How do I handle an input source on a list of objects

In react-admin, I have an input whose source is a list of objects.
<CheckboxGroupInput source="binded_cameras" choices={choices}/>
The binded_cameras list looks like this:
"binded_cameras": [
{
"id": 1,
"name": "Cam 1",
"url": "dummyurl.com"
},
{
"id": 4,
"name": "Cam 2",
"url": "dummyurl.com"
}
]
I am trying to get only the list of id to deal with.I tried binded_cameras.id but of course it did not work.
How do I manipulate this list of objects, and generate only a list of ids?
Since React-admin uses react-final-form, you can it's use parse() and format() functions to transform the input value when saving to and loading from the record, just pass them as props to Input, in this case CheckboxGroupInput:
Mnemonic for the two functions:
parse(): input -> record
format(): record -> input
<CheckboxGroupInput
source="binded_cameras"
choices={choices}
parse={ids => ids.map(id => ({id}))}
format={bindedCameras => bindedCameras.map(b => b.id)}
/>
https://marmelab.com/react-admin/Inputs.html#transforming-input-value-tofrom-record

Getting values of json array in Mocha JS

I have following issue, this json is returned by api:
"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}
and I need to get names of all variables under products array, how to get them?
That values are constantly changing everyday, so I can not refer to their names
Trying console.log(res.body.menu.categories[i].products.values()); but its not worked.
Any sugesstion how can I get 10432471 and 10432481 from products? Without referring to variable names.
You are able to get that via Object.keys(res.body.menu.categories[i].products)
To get the object properties, the shortest is using Object.keys()
var obj = {"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}}
var properties = Object.keys(obj.products)
console.log(properties)

JavaScript Json Array Parsing using Backbone

I have the following sample json:
{
"camp": [
{
"name": "Name",
"data": [
{
"date": "04/08/2014",
"value": 1000
},
{
"date": "05/08/2014",
"value": 1110
}
]
}
]
}
Here, I'm able to do: model.get("camp")[0], but when I try: model.get("camp")[0].get("data"), I get the following error:
undefined is not a function
Here model is the standard backbone model which extends Backbone.Model
I'm confused what I'm doing wrong !!
You only need to call the model.get() function once. After that, you can treat the returned object just like any other javascript-object. For example, you could do this to get one of the values deep inside the object:
model.get("camp")[0].data[0].value
To achieve what you are trying to get, do this:
model.get("camp")[0].data
If you want to acces a property of your json array, you should simply do like this:
var test = json.camp.name
This is how you get your value:
obj.camp[0].data[0]

Parsing a JSON object-within-an-object in javascript

I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work

Categories

Resources