I am using axios to access the OMDB api. The returned value is saved to a ref([]) object called ombdRatings in my vue component, and I'm trying to access these values to be displayed in the DOM. Here's the returned json:
{"Title":"Parasite","Year":"1982","Rated":"R","Released":"12 Mar 1982","Runtime":"85 min","Genre":"Horror, Sci-Fi","Director":"Charles Band","Writer":"Alan J. Adler, Michael Shoob, Frank Levering","Actors":"Robert Glaudini, Demi Moore, Luca Bercovici","Plot":"In a post-apocalyptic USA, a doctor/scientist infected with a new strain of parasite ends up in a small desert town, trying to find a cure.","Language":"English","Country":"United States","Awards":"N/A","Poster":"https://m.media-amazon.com/images/M/MV5BMTFlZDVjMDMtODkwNS00MTM3LWJiMzQtY2IxN2JiNWZjMWUxXkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"4.0/10"},{"Source":"Rotten Tomatoes","Value":"17%"}],"Metascore":"N/A","imdbRating":"4.0","imdbVotes":"2,574","imdbID":"tt0084472","Type":"movie","DVD":"30 Oct 2017","BoxOffice":"N/A","Production":"Embassy Pictures","Website":"N/A","Response":"True"}
The ratings are stored in an array in my object. When I try to access the first item on the array to display in the DOM like: {{ omdbRatings.Ratings[0] }} then I get an error like
Uncaught (in promise) TypeError: Cannot read properties of undefined
(reading '1')
I can access other items in the object, but I don't know how I can access this array in my DOM with interpolation.
when axios is not done ,ratings and Value are undefined,so it is wrong. you can need to ratings is exist。you wirte code:
<div v-if="omdbRatings&&omdbRatings.Ratings&&......">.....</div>
This is tedious.
Simple,code is right.
in js,you can:
console.log(omdbRatings?.Ratings?.[0]?.Value||'--');
but template,you need template supposed Optional_chaining:
export const optionalChaining = (obj, ...rest) => {
let tmp = obj;
for (let key in rest) {
let name = rest[key];
tmp = tmp?.[name];
}
return tmp || "";
}
so,template use:
{{optionalChaining(omdbRatings,"Ratings",'0','Value')||'--'}}
Related
I try to access to my data json file:
[{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}
This is my approach:
data[0].name;
But like this I get only the result:
Animals
But I would need the result:
Animals, Cats
You are accessing only the name property of 0th index of project array.
To access all object at a time you need to loop over the array.
You can use Array.map for this.
var data = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}]
var out = data[0].project.map(project => project.name).toString()
console.log(out)
If that's your actual data object, then data[0].name would give you "Maria". If I'm reading this right, though, you want to get all the names from the project array. You can use Array.map to do it fairly easily. Note the use of an ES6 arrow function to quickly and easily take in the object and return its name.
var bigObject = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}];
var smallObject = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
console.log("Getting the names from the full array/data structure: "+bigObject[0].project.map(obj => obj.name))
console.log("Getting the names from just the project array: "+smallObject.map(obj => obj.name))
EDIT: As per your comment on the other answer, you said you needed to use the solution in this function:
"render": function (data, type, row) {if(Array.isArray(data)){return data.name;}}
To achieve this, it looks like you should use my bottom solution of the first snippet like so:
var data = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
function render(data, type, row){
if(Array.isArray(data)){
return data.map(obj => obj.name);
}
};
console.log("Render returns \""+render(data)+"\" as an array.");
I am new to both JSON and Postman(as of yesterday).
I'm trying to do something very simple, I've created a GET request which pulls in a list of forms in a JSON response. I want to take this response and get the first "id" token and place it in a variable.
I am using a global variable but would like to use a collection variable if possible. Either way here is what I am doing.
I've tried several things, most recently this:
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("id", jsonData.args.id);
As well as this:
pm.test("GetId", function () {
var jsonData = pm.response.json();
pm.globals.set("id", jsonData.id);
});
Response code looks like this:
{
"forms":[
{
"id":"3197239",
"created":"2018-09-18 11:37:39",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Contact Us",
"num_columns":"2",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:02:13",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
},
{
"id":"3197245",
"created":"2018-09-18 11:42:02",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Football Draft",
"num_columns":"1",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:11:54",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxxxxxxxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
}
]
}
This would get the first id:
pm.globals.set('firstId', _.first(pm.response.json().forms).id)
That would get the first in the array each time so it would set a different variable it that response changed.
The test that you created was nearly there but the reference needed to go down a level into the forms array:
pm.test("GetId", function () {
var jsonData = pm.response.json()
pm.expect(jsonData.forms[0].id).to.equal("3197239")
pm.globals.set("id", jsonData.forms[0].id)
})
The [0]is referencing the first id in the first object within the array. For example [1] would get the second one and so on.
You currently cannot set a collection level variable using the pm.* API - These can only be added manually and referenced using the pm.variables.get('var_name') syntax.
Edit:
In the new versions of the desktop app you can set variables at the Collection level using pm.collectionVariables.set().
Based on the name or any other attribute if you want to set the id as a global variable then this is the way.
for(var i=0; i<jsonData.forms.length; i++)
{
if (jsonData.forms[i].name==="Contact Us")
{
pm.environment.set("id", jsonData.forms[i].id);
}
}
So here is the set up:
I have simple nodejs backend (based on express and mongoose), which responds to GET request with some JSON (in the form of Object of objects).
So after I get the response, I want to render a component, for each elements of said Object of objects. If it was array, I could simply use array.map(), and render a component in the callback function. But since what I have, is Object, i can not use that.
So... Should I return and Array from the backend. If so how do I tell mongoose to return the result of model.find() in the form of array.
Or should I convert the object to array in the frontend? In this case, how would I do it without putting it through a loop of some sort?
Lastly, I tried to make it work like so:
render: function() {
//console.log('render TodoList componenr');
var items = this.state.todoItems;
return(
<ul>
{for (var item in items){
console.log(item);
}}
</ul>
);
}
To which i get this error:
Uncaught SyntaxError: embedded: Unexpected token (30:9)
28 | return(
29 | <ul>
> 30 | {for (var item in items){
| ^
31 |
32 | }}
33 | </ul>
Which is super weird, as it points to empty location?
Any ideas how could make this work?
To iterate over an object you could use Object.keys like so:
Object.keys(yourObject).map(function(key) {
return renderItem(yourObject[key]);
});
The method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
It's supported by IE >= 9, Chrome >= 5, Safari >= 5, Firefox >= 4.
You can setting the object.map function equal to a variable outside the return function and then just return that variable.
render() {
var article = this.props.article;
var articleNodes = article.map(function(article, key){
if(article.iurl == ""){
article.iurl = "basketball.jpg";
};
return(
<li key={key}>
<Image item={article}/>
<div className="post-basic-info">
<h3><a target="_blank" href={article.url}>{article.title}</a></h3>
<span><label> </label>{article.team}</span>
<p>{article.description}</p>
</div>
</li>
)
});
return(
<div>
{articleNodes}
</div>
)
}
I'm using jade templates for my templating system, passing a json file in as the jade locals via my gulpfile.js, but I can't seem to deep dive into the json. I feel like I'm overlooking something basic, but can't find an example online anywhere.
gulpfile.js:
Passes the json file into jade
gulp.task('html', function() {
gulp.src('./markup/*.jade')
.pipe(jade({
pretty: true,
locals: JSON.parse( fs.readFileSync('./markup/data/website_data.json', { encoding: 'utf8' }) )
}).on('error', gutil.log))
.pipe(gulp.dest('../'))
});
Then in my jade, I just pass the locals into a variable for the sake of readability.
- var employees = locals
And I can loop through json that is one level deep:
jade:
for employee in employees
if employee.Tier === 'Founder'
li
button(data-bio="#{employee.LastName.toLowerCase()}")
img(src="/public/img/employees/#{employee.FirstName.toLowerCase()}-#{employee.LastName.toLowerCase()}.jpg", alt="#{employee.FirstName} #{employee.LastName} | #{employee.Title}")
strong #{employee.FirstName} #{employee.LastName}
| #{employee.Title}
json:
[
{
"FirstName":"John",
"LastName":"Doe",
"Title":"Strategist",
"Tier":"Founder",
"Description":"",
"Email":"",
"Links":""
},
...
]
But that has only worked for me if the items I loop through are in the root, as soon as I make the json one level deeper, I can't get it to work based on the key. I want to make the json deeper so I can different sections of a site in it instead of just the employees.
[{
"employees": [
{
"FirstName":"Jason",
"LastName":"Bellinger",
"Title":"Lorem Ipsum",
"Tier":"",
"Description":"",
"Email":"",
"Links":""
},
...
]
}]
I tried a few different approaches to to dig into the json and have failed thus far.
ATTEMPT 1: adjust the variable call and keep the same loop
- var employees = locals.employees
And I get 'Cannot read property 'length' of undefined' in the terminal running $gulp watch
Also try:
- var employees = locals['employees']
to the same result.
ATTEMPT 2: don't use the var and call locals directly in my loop
for employee in locals.employees
AND
for employee in locals["employees"]
And I end up with the same error.
ATTEMPT 3:
keep the var and adjust the loop
- var employees = locals
...
for employee in employees
li #{employee.LastName}
Then I don't get an error in Terminal, but I don't get any content. It produces one empty li.
So then, I try to go a layer deeper in the loop with:
for employee in employees[0]
li #{employee.LastName}
AND
for employee in employees['employees']
li #{employee.LastName}
AND I still get no error and one empty li
I've parsed enough json in my day and jade seems simple enough, I have to be overlooking something basic. Someone please humble me.
I also dabbled in gulp-data, but I'm getting the data into jade with my approach, so I think it's my approach in jade...
You need to access the array inside you locals variable.
The length of local = 1 and that is the entire array of employees.
You'll need to set employees = to the array inside of the locals variable with:
"- var employees = locals[0].employees"
I knew it was something basic. I reverted everything back to the original setup and changed the var and this is working.
- var employees = locals[0]['employees']
Truth be told, I thought I already tried this, but went back and tried again...
I have a json string: {"jsonrpc":"2.0","result":[{"event":{"id":"27151641","name":"TSW Pegasus FC (Res) v Sun Hei SC (Res)","countryCode":"HK","timezone":"GMT","openDate":"2014-02-19T12:30:00.000Z"},"marketCount":14},{"event":{"id ":"27151646","name":"Humble Lions v Boys Town FC... etc etc
So the result bit is a list of event/marketcount pairs. I've used the parse method in a class module called jsonlib which I got from http://code.google.com/p/vba-json/issues/attachmentText?id=15&aid=150001000&name=jsonlib.cls&token=31ObtlGBtaGXd2KR0QLyffX_x8Y:1359742317106
This creates an object (jason_obj) which represents the result bit above. Now I want to get a list of ids for each event. I can use the for each ... construct to return each event/marketcount pair as an object, but I can't work out how to get to the id field that is somewhere in the event object. I tried to use the tostring method to get a clue, and from that this code should work but it doesn't:
For Each eventItem In jason_obj
this_eventx = eventItem("event")
this_id = this_eventx("id")
Next
Don't know much about accessing objects/collections. Can anyone help? Thanks
Objects need to be set and references should use item:
For Each eventItem In jason_obj
set this_eventx = eventItem.item("event")
this_id = this_eventx.item("id")
Next
HTH
Yes it did