get value of elements in NodeList - javascript

I'm a bit confused about some expected behavior regarding NodeLists, and was hoping that someone could point me in the right direction.
So I have a hidden input element whose value attribute holds a json string with a bunch of s3 upload data. It looks like this:
<input
name="uppyResult"
type="hidden"
value="[
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-screen/shot/2021/07/15/at/4/00/02/pm/png-10-10-1d-1d-10-10-1e-1e-10-1e-image/png-165186-1626390007842",
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"extension":"png",
"meta":{
"relativePath":null,
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"type":"image/png",
"key":"cache/4870f1e1d9f075c7397b3422f101f7e4.png",
"Content-Disposition":"inline; filename=\"Screen Shot 2021-07-15 at 4.00.02 PM.png\"; filename*=UTF-8''Screen%20Shot%202021-07-15%20at%204.00.02%20PM.png",
"Content-Type":"image/png",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMDo0M1oiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvNDg3MGYxZTFkOWYwNzVjNzM5N2IzNDIyZjEwMWY3ZTQucG5nIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cIlNjcmVlbiBTaG90IDIwMjEtMDctMTUgYXQgNC4wMC4wMiBQTS5wbmdcIjsgZmlsZW5hbWUqPVVURi04JydTY3JlZW4lMjBTaG90JTIwMjAyMS0wNy0xNSUyMGF0JTIwNC4wMC4wMiUyMFBNLnBuZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvcG5nIn0sWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MF0seyJ4LWFtei1jcmVkZW50aWFsIjoiQUtJQTNKRVpaRkFOTzNCNlI0VE8vMjAyMTA4MjcvdXMtd2VzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LHsieC1hbXotYWxnb3JpdGhtIjoiQVdTNC1ITUFDLVNIQTI1NiJ9LHsieC1hbXotZGF0ZSI6IjIwMjEwODI3VDIyMjA0M1oifV19",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222043Z",
"x-amz-signature":"8478e24c985b7517399dd3278591e283584403c666983b1d6900c3d4c0b594d5"
},
"type":"image/png",
"data":{},
"progress":{
"uploadStarted":1630102841653,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":167201,
"bytesTotal":167201,
"postprocess":null
},
"size":165186,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/ab73e53f-7b2c-4a77-aade-07f216b31d27",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,"isPaused":false
}
],
"failed":[],
"uploadID":"cksux56ic00013h63szerkigt"
},
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-blackdog/parkerbright/servitude2017/jpg-2v-2v-1e-image/jpeg-24872-1613012190277",
"name":"blackdog_parkerbright_servitude2017.jpg",
"extension":"jpg",
"meta":{
"relativePath":null,
"name":"blackdog_parkerbright_servitude2017.jpg",
"type":"image/jpeg",
"key":"cache/da42d10f2b1f47b004654b257df07a01.jpg",
"Content-Disposition":"inline; filename=\"blackdog_parkerbright_servitude2017.jpg\"; filename*=UTF-8''blackdog_parkerbright_servitude2017.jpg",
"Content-Type":"image/jpeg",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMTozMVoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvZGE0MmQxMGYyYjFmNDdiMDA0NjU0YjI1N2RmMDdhMDEuanBnIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cImJsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZ1wiOyBmaWxlbmFtZSo9VVRGLTgnJ2JsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvanBlZyJ9LFsiY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjBdLHsieC1hbXotY3JlZGVudGlhbCI6IkFLSUEzSkVaWkZBTk8zQjZSNFRPLzIwMjEwODI3L3VzLXdlc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWRhdGUiOiIyMDIxMDgyN1QyMjIxMzFaIn1dfQ==",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222131Z",
"x-amz-signature":"a17970d6b111ed0acb535342433626ec7d277fd6364517bb3ee9c02de529f0d7"
},
"type":"image/jpeg",
"data":{},
"progress":{
"uploadStarted":1630102891533,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":26864,
"bytesTotal":26864,
"postprocess":null
},
"size":24872,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/79066114-d51b-4ef4-b62a-af8ac80ae617",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,
"isPaused":false
}
],
"failed":[],
"uploadID":"cksux68zv00033h63tzjc85kg"
}
]"
>
When I log document.getElementsByName("uppyResult") to console, it shows up as a NodeList. Which apparently is sort of like an array, but not? The data I need to access in this NodeList takes a click and a scroll to get to - I simply expand the input and scroll to defaultValue.
What I need is access to every successful object in this NodeList. There can be one or many. Note that this one has two.
My last attempt at doing this same thing was botched because I misunderstood what I was trying to do. Though the selected answer did solve the problem as I phrased it, what I needed was to perform the same action for more than just the initial [0] item. Each uploaded batch of files occupies an index in this array, and I need to get all of them.
The old code from that answer is:
if (reason === 'removed-by-user') {
const preParsedData = document.getElementsByName("uppyResult")[0].value //this is the problem, i think - i need *all* the elements in the array/NodeList
const parsedData = JSON.parse(preParsedData)
const toRemove = file.id
parsedData.forEach(item => {
Object.values(item).forEach(array => {
if (!Array.isArray(array))
return;
const index = array.findIndex(elm => elm.id === toRemove)
if (index > -1)
array.splice(index, 1)
});
if (item.successful.length === 0)
delete item.successful
delete item.failed
delete item.uploadID
});
console.log(parsedData)
document.getElementsByName("uppyResult")[0].value = JSON.stringify(parsedData)
}
})

In case if you "need all the elements in the array/NodeList" you have to go through all nodes with other forEach call.
So, it will looks like:
const inputEls = document.getElementsByName("uppyResult")
inputEls.forEach((node) => {
// here run the code you already have
const preParsedData = node.value
const parsedData = JSON.parse(preParsedData)
....
}

Before you parse the data in value it has to be a valid JSON string. For that, you have to replace every instance of " by " using the .replace() method so that it becomes a valid JSON string to be parsed.
const preParsedData = document.getElementsByName("uppyResult")[0].value.replace(""","\"");
const parsedData = JSON.parse(preParsedData);
console.log(parsedData);
<html>
<head>
<title>Title</title>
</head>
<body>
<input name="uppyResult" type="hidden" value="[
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-screen/shot/2021/07/15/at/4/00/02/pm/png-10-10-1d-1d-10-10-1e-1e-10-1e-image/png-165186-1626390007842",
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"extension":"png",
"meta":{
"relativePath":null,
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"type":"image/png",
"key":"cache/4870f1e1d9f075c7397b3422f101f7e4.png",
"Content-Disposition":"inline; filename=\"Screen Shot 2021-07-15 at 4.00.02 PM.png\"; filename*=UTF-8''Screen%20Shot%202021-07-15%20at%204.00.02%20PM.png",
"Content-Type":"image/png",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMDo0M1oiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvNDg3MGYxZTFkOWYwNzVjNzM5N2IzNDIyZjEwMWY3ZTQucG5nIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cIlNjcmVlbiBTaG90IDIwMjEtMDctMTUgYXQgNC4wMC4wMiBQTS5wbmdcIjsgZmlsZW5hbWUqPVVURi04JydTY3JlZW4lMjBTaG90JTIwMjAyMS0wNy0xNSUyMGF0JTIwNC4wMC4wMiUyMFBNLnBuZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvcG5nIn0sWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MF0seyJ4LWFtei1jcmVkZW50aWFsIjoiQUtJQTNKRVpaRkFOTzNCNlI0VE8vMjAyMTA4MjcvdXMtd2VzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LHsieC1hbXotYWxnb3JpdGhtIjoiQVdTNC1ITUFDLVNIQTI1NiJ9LHsieC1hbXotZGF0ZSI6IjIwMjEwODI3VDIyMjA0M1oifV19",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222043Z",
"x-amz-signature":"8478e24c985b7517399dd3278591e283584403c666983b1d6900c3d4c0b594d5"
},
"type":"image/png",
"data":{},
"progress":{
"uploadStarted":1630102841653,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":167201,
"bytesTotal":167201,
"postprocess":null
},
"size":165186,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/ab73e53f-7b2c-4a77-aade-07f216b31d27",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,"isPaused":false
}
],
"failed":[],
"uploadID":"cksux56ic00013h63szerkigt"
},
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-blackdog/parkerbright/servitude2017/jpg-2v-2v-1e-image/jpeg-24872-1613012190277",
"name":"blackdog_parkerbright_servitude2017.jpg",
"extension":"jpg",
"meta":{
"relativePath":null,
"name":"blackdog_parkerbright_servitude2017.jpg",
"type":"image/jpeg",
"key":"cache/da42d10f2b1f47b004654b257df07a01.jpg",
"Content-Disposition":"inline; filename=\"blackdog_parkerbright_servitude2017.jpg\"; filename*=UTF-8''blackdog_parkerbright_servitude2017.jpg",
"Content-Type":"image/jpeg",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMTozMVoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvZGE0MmQxMGYyYjFmNDdiMDA0NjU0YjI1N2RmMDdhMDEuanBnIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cImJsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZ1wiOyBmaWxlbmFtZSo9VVRGLTgnJ2JsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvanBlZyJ9LFsiY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjBdLHsieC1hbXotY3JlZGVudGlhbCI6IkFLSUEzSkVaWkZBTk8zQjZSNFRPLzIwMjEwODI3L3VzLXdlc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWRhdGUiOiIyMDIxMDgyN1QyMjIxMzFaIn1dfQ==",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222131Z",
"x-amz-signature":"a17970d6b111ed0acb535342433626ec7d277fd6364517bb3ee9c02de529f0d7"
},
"type":"image/jpeg",
"data":{},
"progress":{
"uploadStarted":1630102891533,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":26864,
"bytesTotal":26864,
"postprocess":null
},
"size":24872,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/79066114-d51b-4ef4-b62a-af8ac80ae617",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,
"isPaused":false
}
],
"failed":[],
"uploadID":"cksux68zv00033h63tzjc85kg"
}
]">
</body>
</html>

Related

Retrieve data from the json file in JavaScript and display flower and color in different ul

Retrieve data from the json file in JavaScript and display flower and color in different ul,
i am try to add but trouble here how can i make it,
fetch('dataFiles/midterm.json', {
method: 'GET',
mode: 'no-cors'
})
.then((response) => response.text())
.then((data) => {
//console.log(JSON.parse(data));
//data = response.text();
alert(data);
console.log(data);
document.getElementById("data").innerHTML += "<ul></ul>";
document.getElementById("data").innerHTML += "<ul></ul>";
// Process data
})
.catch ( (err) => { // Process Error
});
// json here
{ "inventory": [
{"type": "flower",
"cars": [
{ "make" : "VW","model" : "Bug","cost" : 24000 },
{ "make" : "GMC","model" : "Suburban","cost" : 18000 }]},
{"type": "color",
"cars": [
{ "make" : "VW","model" : "Jetta","cost" : 25000 },
{ "make" : "Chevy","model" : "Tahoe","cost" : 30000 },
{ "make" : "FORD","model" : "F150","cost" : 29000 },
{ "make" : "HYUNDAI","model" : "Elantra","cost" : 27500 }]}
]
}
Create and add list items
The problem with your code is that <ul> are added, but without any list items <li>. There is nothing to display.
To fix the problem, build an html string from the fetched data. You can do this using an outer and inner forEach loop to display the child array "cars" within each inventory type, i.e., flowers and colors.
You can use template literals to build the html and then display the complete list in the data element as shown.
Snippet
Review and run the snippet to understand how it works.
let data ={"inventory":[{"type":"flower","cars":[{"make":"VW","model":"Bug","cost":24000},{"make":"GMC","model":"Suburban","cost":18000}]},{"type":"color","cars":[{"make":"VW","model":"Jetta","cost":25000},{"make":"Chevy","model":"Tahoe","cost":30000},{"make":"FORD","model":"F150","cost":29000},{"make":"HYUNDAI","model":"Elantra","cost":27500}]}]};
// inside fetch.then(
let html = "";
data.inventory.forEach(item => {
html += `<h4>${item.type}</h4><ul>`;
item.cars.forEach(car => {
html += `<li>${car.make}, ${car.model}, ${car.cost}</li>`;
});
html += "</ul>";
});
document.querySelector("#data").innerHTML = html;
h4 {
background-color: steelblue;
color:white;
padding: 0.2rem;
}
<div id="data"></div>

How to get array length with Expression Binding?

As the title implies, I do have the following data:
{
"modelExample": [
{ "id": 0 },
{ "id": 1 },
{ "id": 2 }
]
}
The JSONModel has three entries, which essentially equates to 3 in length.
How do I get the length through an Expression Binding statement?
My Attempt:
<Text text="{ ${modelExample>/}.length}"
OK, here is a sample. Click on Run code snippet to see it in action:
sap.ui.require([
"sap/ui/core/Core",
], Core => Core.attachInit(() => sap.ui.require([
"sap/ui/core/Fragment",
"sap/ui/model/json/JSONModel",
], async (Fragment, JSONModel) => {
"use strict";
// sample XML definition:
const definition = '<ObjectStatus title="Length" text="{= ${/modelExample}.length}" class="sapMObjectStatusLarge sapUiTinyMargin" inverted="true" state="Information" xmlns="sap.m" />';
const control = await Fragment.load({ definition });
const model = new JSONModel({
modelExample: [
{ id: 0, /*...*/},
{ id: 1, /*...*/},
{ id: 2, /*...*/},
],
});
control.setModel(model).placeAt("content");
})));
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-libs="sap.ui.core, sap.m"
data-sap-ui-async="true"
data-sap-ui-compatversion="edge"
data-sap-ui-theme="sap_fiori_3"
data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody"></body>
As you can see, I'm using text="{= ${/modelExample}.length}" which displays the correct length of the array:
If the model is named (e.g. "myModel"), it should be {= ${myModel>/modelExample}.length}.
Keep in mind that expression binding syntax requires {= (OneWay) or {:= (OneTime) at the beginning.
To actually make use of the expression binding, the bootstrap config bindingSyntax needs be set to "complex" or compatVersion to "edge", as mentioned in this post. E.g. in index.html:
<script id="sap-ui-bootstrap" data-sap-ui-compatversion="edge" ...>

How to Check value in JSON object ionic2

How to check "no_cover" value in thumbnail[0] and replace it to asset/sss.jpg for show listpage
I try to set <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html ,this show only thumbnail[0] is http://xxx.jpg, http://xxx.jpg , ,But I have no idea to set "no_cover"
myjson
" DOCSET":{
"DOC":[
{
"LINKS":{
"thumbnail":"http://yyy.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"http://xxx.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"no_cover", <<<<
"thumbnail":"http://....jpg"}
}]
}
EDIT - HOW YOUR JSON SHOULD LOOK
Since I (ivaro18) believe you wrote your JSON by hand and did not copy a response object. Let me show you what valid JSON looks like:
{
"DOCSET" : [
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "no_cover"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
}
]
}
END OF EDIT
listpage.html
<ion-list>
<ion-item *ngFor="let item of foundRepos">
<ion-thumbnail item-left >
<img src="{{item.LINKS.thumbnail[0]}}"> <!--I have no idea to set it -->
</ion-thumbnail>
</ion-list>
list.page.ts
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos = data.json().DOCSET.DOC;
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
So, first of all your JSON you've posted was invalid. edited your question with what it probably is (since you are printing it as you say)
What I understand from your problem is the following, you have <img src="{{item.LINKS.thumbnail[0]}}"> but this throws a 404 when no_cover is returned, that's why, when item.LINKS.thumbnail[0] is equal to 'no_cover' you want to show the image assets/sss.jpg
So, how can we use this to show 'assets/sss.jpg' instead of 'no_cover'? It's called the Elvis operator ( ? : )
Let's assume the following construction for an if-statement:
if(expression) {
result = whenExpressionIsTrue
} else {
result = whenExpressionIsFalse
}
Which we can rewrite with the Elvis operator like this:
result = someExpression ? whenExpressionIsTrue : whenExpressionIsFalse
So, let's check out your problem, how can we do this with an if-statement?
if(item.LINKS.thumbnail[0] == 'no_cover') {
someVariable = 'assets/sss.jpg';
} else {
someVariable == item.LINKS.thumbnail[0];
}
Now shorten it with the Elvis operator:
someVariable = item.LINKS.thumbnail[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnail[0];
Now this can be used in your HTML like so:
<img
[src]="item.LINKS.thumbnails[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnails[0]"
/>

Accessing JSON element which has a number for the name

I have tried to access an element of the json structure but can't. I have tried the following.
I am using the npm package json-query to extract part of the bigger JSON object.
var rslt = jsonQuery('results[**][* status=active]', {
data: response
});
var make = JSON.stringify(rslt.value[0]["parms"]["make"])
Bu this does not work, I have also tried to get the following data from the JSON:
var img = JSON.stringify(rslt.value[0]["photos"]["1"]["320x240"]);
var subtitle = JSON.stringify(rslt.value[0]["parms"]["price"]["1"]) + ' EUR';
This is the JSON data I am working with:
{
"value":[
{
"id":7038271775,
"user_id":1307227,
"status":"active",
"title":"",
"url":"https://www.autovit.ro/anunt/nissan-navara-ID7GjS0w.html",
"created_at":"2017-01-06 17:49:35",
"valid_to":"2017-02-03 17:56:16",
"description":"Data inmatriculare: 02.03.2015.\r\n4x4 \r\nABS \r\nAer conditionat \r\nComputer de bord \r\nGeamuri electrice \r\nInchidere centralizata \r\nJante aliaj \r\nRadio CD \r\nServodirectie \r\nVolan multifunctional",
"category_id":29,
"region_id":46,
"city_id":24691,
"city":{
"ro":"Voluntari",
"en":"Voluntari"
},
"coordinates":{
"latitude":44.49192877,
"longitude":26.12458706,
"radius":0,
"zoom_level":16
},
"advertiser_type":"business",
"contact":{
"person":"LeasePlan Outlet Center",
"phone_numbers":[
"0753312151"
]
},
"params":{
"make":"nissan",
"model":"navara",
"year":2014,
"mileage":16785,
"engine_capacity":2500,
"vin":"VSKCVND40U0566467",
"fuel_type":"diesel",
"gearbox":"manual",
"transmission":"all-wheel-lock",
"particle_filter":"0",
"green_tax":"1",
"damaged":"0",
"body_type":"suv",
"door_count":4,
"color":"white",
"metallic":"0",
"pearl":"0",
"matt":"0",
"rhd":"0",
"features":[ ],
"price":{
"0":"price",
"1":15900,
"currency":"EUR",
"gross_net":"net"
},
"vat":"1",
"financial_option":"1",
"leasing_concession":"0",
"date_registration":"2014-1-01",
"registered":"1",
"original_owner":"1",
"no_accident":"0",
"service_record":"0",
"historical_vehicle":"0",
"tuning":"0"
},
"photos":{
"1":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_1_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_1_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_1_148x110.jpg"
},
"2":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_2_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_2_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_2_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_2_148x110.jpg"
},
"3":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_3_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_3_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_3_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_3_148x110.jpg"
},
"4":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_4_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_4_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_4_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_4_148x110.jpg"
},
"5":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_5_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_5_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_5_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_5_148x110.jpg"
},
"6":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_6_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_6_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_6_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_6_148x110.jpg"
},
"7":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_7_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_7_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_7_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_7_148x110.jpg"
},
"8":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_8_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_8_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_8_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_8_148x110.jpg"
},
"9":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_9_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_9_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_9_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_9_148x110.jpg"
},
"10":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_10_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_10_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_10_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_10_148x110.jpg"
},
"11":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_11_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_11_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_11_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_11_148x110.jpg"
}
},
"image_collection_id":820558483,
"last_update_date":"2017-01-24 18:00:26",
"new_used":"used"
}
],
"is_last_page":false,
"is_first_page":true,
"current_page":1,
"total_pages":33,
"current_elements":1,
"total_elements":33
}
I don't know what excatly "json-query" does but I think you can extract any JSON part safely like this;
function dig(input, key) {
var keys = (""+ key).split("."), key = keys.shift();
if (!keys.length) {
return input[key];
}
return dig(input[key], keys.join("."));
}
// here that gives me already without any error thrown >> https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg
var p = dig(rslt, "results.0.photos.1.320x240");
console.log(p);
// this is same with
console.log(rslt.results[0].photos[1]["320x240"]);
Credits: https://github.com/yay-couch/couch-js/blob/master/couch/util/util.js#L46
i'm not sure how its not working, the only problem i see with your code is you mistaken by writing params and you write parms

Selecting JSON object data table element to list all its elements

I'm working on something that's a little over my head and I can't seem to find any libraries that relate to this. In the web application that I'm working on, I have a list of n people and upon clicking on a person's name, a list of n articles written by that person will be generated. I am trying to accomplish this using JavaScript and JSON.
This is how my JSON data will be structured:
var people = {
'clients': [
{
'fname': 'joe',
'lname': 'smith',
'AFD': [
{
'articleName': 'AFDArticle1byjoe'
},
{
'articleName': 'AFDArticle2byjoe'
},
{
'articleName': 'AFDArticle3byjoe'
},
{
'articleName': 'AFDArticle4byjoe'
},
{
'articleName': 'AFDArticle5byjoe'
}
]
},
{
'fname': 'jim',
'lname': 'Hoff',
'AFD': [
{
'articleName': 'AFDArticle12byjim'
}
]
},
{
'fname': 'rick',
'lname': 'Robinson',
'AFD': [
{
'articleName': 'AFDArticle5byrick'
}
]
},
{
'fname': 'sarah',
'lname': 'Ross',
'AFD': [
{
'articleName': 'AFDArticle20bysarah'
}
]
},
{
'fname': 'jack',
'lname': 'jones',
'AFD': [
{
'articleName': 'AFDArticle9byjack'
}
]
}
]
};
Everyone has a first name, last name, and a list of n AFD Articles.
This code will nicely list out the number of n people in an HTML table from the JSON example above:
<table border="1">
<script>
for (var i=0;i<people.clients.length;i++)
{
$("#tabX").append("<tr><td>"+people.clients[i].fname+"</td></tr>");
}
</script>
</table>
and so I'll get some nice output of the first names in a table like so:
"joe jim rick sarah jack"
And so by clicking on "joe", a data table of Joe's articles will be generated. I can already accomplish this like so:
<table border="1">
<script>
for (var i=0;i<people.clients.length;i++)
{
$("#tabX").append("<tr><td>"+people.clients[ selectedClient ].AFD[i].articleName+"</td></tr>");
}
</script>
</table>
Where "selectedClient" is the client that's currently selected, AFD articles will be generated like so: AFD Article 1 by joe, ... , AFD Article 4 by joe.
So finally! I have some questions that would really help me get through this. How could I change the value of selectedClient after clicking on someone's name? Could this be possibly done by executing a function like below?
$("#tabX").append("<tr><td>" +people.clients[i].fname+ "</td></tr>");
I think you are on the right track. May be something like this will help:
$("#tabX").append("<tr><td>" +people.clients[i].fname+ "</td></tr>");
and then this will be your selectName function:
function selectName (idx)
{
selectedClient = idx;
}
Here's how I would approach it.
I assume the following HTML:
<table id="people"></table>
<div id="articles"></div>
And the following Javascript. forEach is IE9 and above.
So for each person on your client list, add them to the table, ensuring that you set the data id to that client's index in the JS object, and include a class name.
people.clients.forEach(function(el, i) {
$('#people').append('<tr><td data-id="' + i + '" class="name">' + el.fname + '</td></td>');
});
Then, when you click on an element with a name class name, pick up the id from the data attribute, loop through the AFDs for that client using the id and append them to the div (or element of your choice.). This makes the further assumption that between the time you list your clients and you start clicking on their names you're not sorting the people object, otherwise the indexes (ids) will be all out of wack.
$('.name').click(function() {
var id = $(this).data('id');
people.clients[id].AFD.forEach(function(el, i){
$('#articles').append('<div>' + el.articleName + '</div>');
});
});
JSfiddle

Categories