Loop through json array with objects - javascript

I´ve got an array in this format:
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2"
}
}]
I can´t figure out how to loop through it and display its values in HTML.
Im using jquery and have tried using an each-loop:
$.each( items, function(i, item) {
console.log(item); // Uncaught TypeError: Cannot use 'in' operator to search for '6271' in
})
Help appreciated. Thanks!
EDIT:
Your code works in the example i posted above. I will accept asasp.
I noticed however that the real json im trying to loop is not always properly formatted which leads to a crash:
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2: "
some text here ""
}
}]
When looping this array i get:
Uncaught SyntaxError: Unexpected identifier
Is there a way to maybe skip all "broken" objects?

Here you go with a solution
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2"
}
}];
$.each( items, function(i, item) {
$("body").append(`<span class="title">${item.title["0"]}:</span> <span>${item.link["0"]}</span><br/>`);
});
.title {
font-weight: bold;
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Each item is an object, to get the link value I've provided in the solution.

Fast and dirty:
for (item of items) {
console.log(item.link[0])
console.log(item.title[0])
}

Related

How do I check if a nested JSON property exists and how many nested properties it has?

This quandary of mine is mainly based on the number of levels of complexity. I'm trying to figure out the JavaScript logic, but the JSON syntax gets complicated too, so any suggestions are appreciated.
I have a JSON file with more or less the following structure, except I have a whole lot more properties of each code type:
[{
"000": {
"code": "A",
"description": "Poor circulation",
},
"001": {
"code": "B",
"description": "Pain in foot",
"subCodes": {
"0": {
"Right":"1",
"Left":"2"
}
}
},
"003": {
"code": "C",
"description": "Exostosis",
"subCodes": {
"0": {
"Ankle":"1",
"Foot":"2",
"Leg":"3",
"Thigh":"4"
}
}
},
}]
The majority of the codes are like code A, and they're to be left alone. However, I need to filter and mark all codes that are like B (that is, having a "subcodes" property AND just the two nested properties "Right" and "Left") to have a '+' next to them; and codes like C (with any subcodes but just "Right" and "Left") to be marked with a '*'.
Assuming I set a variable for the JSON file, how can I filter these? The rest of my code pushes all the descriptions into an array and the codes into an array to feed them into a div, but how can I have an array alongside with just the codes that have subcodes, and then further filter them according to their child values?
Basically, my end goal is to have a div with all the codes like this:
A Poor circulation
B + Pain in foot
C * Exostosis
Should I abandon the array method altogether? Is there a simpler way? I'm using just vanilla JavaScript.
You could just iterate the object's values and check the conditions.
function getValues(data) {
return data.reduce(
(r, o) => r.concat(
Object
.values(o)
.map(({ code, description, subCodes }) => [
code,
subCodes ? 'Left' in subCodes[0] && 'Right' in subCodes[0] ? '+' : '*' : ' ',
description
].join(' '))),
[]
);
}
var data = [{ "000": { code: "A", description: "Poor circulation" }, "001": { code: "B", description: "Pain in foot", subCodes: { "0": { Right: "1", Left: "2" } } }, "003": { code: "C", description: "Exostosis", subCodes: { "0": { Ankle: "1", Foot: "2", Leg: "3", Thigh: "4" } } } }];
console.log(getValues(data));
Quick and dirty reduce hack that fits you end goal of having a div like this
A Poor circulation
B + Pain in foot
C * Exostosis
const data = {
"000": {
"code": "A",
"description": "Poor circulation",
},
"001": {
"code": "B",
"description": "Pain in foot",
"subCodes": {
"0": {
"Right": "1",
"Left": "2"
}
}
},
"003": {
"code": "C",
"description": "Exostosis",
"subCodes": {
"0": {
"Ankle": "1",
"Foot": "2",
"Leg": "3",
"Thigh": "4"
}
}
},
};
let divElement = "<div>\n";
const reduceToDiv = (acc, curr) => {
if (data[curr]["code"]) {
const description = data[curr]["description"];
if (data[curr]["subCodes"]) {
const subCodes = data[curr]["subCodes"][0];
if ("Left" in subCodes && "Right" in subCodes) acc.push("B + " + description);
else acc.push("C * " + description);
} else acc.push("A " + description);
}
return acc;
};
divElement += Object.keys(data).reduce(reduceToDiv, []).join("\n") + "\n</div>";
console.log(divElement);
Your initial input is an array with one element, I don't know if you did it on purpose but this works with your given array:
const input = [{
"000": {
"code": "A",
"description": "Poor circulation",
},
"001": {
"code": "B",
"description": "Pain in foot",
"subCodes": {
"0": {
"Right":"1",
"Left":"2"
}
}
},
"003": {
"code": "C",
"description": "Exostosis",
"subCodes": {
"0": {
"Ankle":"1",
"Foot":"2",
"Leg":"3",
"Thigh":"4"
}
}
},
}];
const filterJson = arr => {
return Object.values(arr[0]).map(el => !el.hasOwnProperty('subCodes') ? `A ${el.description}` : JSON.stringify(el.subCodes).includes('Right') && JSON.stringify(el.subCodes).includes('Left') ? `B +${el.description}` : `C *${el.description}`);
}
console.log(filterJson(input));

cannot update an array of elements via a 2d iteration

I have two arrays of object, the first array (printerChart, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
},
....
]
The second array (items, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "hp"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do is to iterate via the second array and, if the part of the name of an item (i.e. DT8) is included in an element of the array 'compatibility' of the first array, I would like to include a new properties to it from the element of the first array: printerBrand. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
items.forEach((item) => {
printerChart.forEach((printer) => {
if (printer.compatibilty.some(compatibleElem => (
item.name.includes(compatibleElem)))) {
item.printerBrand = printer.printerBrand;
} else {
item.printerBrand = '';
}
});
});
What am I doing wrong?
You do
items.items.forEach(...)
Shouldn't you be doing
items.forEach(...)
?
I suggest to initialize item.printerBrand with an empty string and use a nested approach of some for getting a brand and to exit the loops, if found.
This prevents to get an empty string even if there is a brand to assign.
items.forEach((item) => {
item.printerBrand = '';
printerChart.some(printer => {
if (printer.compatibilty.some(compatibleElem => item.name.includes(compatibleElem))) {
item.printerBrand = printer.printerBrand;
return true;
}
});
});

How to get the value of a deep nested json object?

I'm working on an app in javascript, and I have this json object (this is a simplified example of the actual json object)
{
"data": [
"user": {
"pictures"{
"sizes"[
0: {
"link": "http://www"
},
1: {
"link": "http://"
}
]
}
}
]
}
And I want to get the value of link, so i tried data.user.pictures.sizes[0].link, and it returned an error. How to get the right value?
edit: I'm using a map function to loop around the data object, so i can display values in an html page. it works for most of the other items, except for pictures sizes, i cant seem to get the value of the second item in the sizes array.
From the data, it shows that 'data' contains array and sizes contains array that contains object of properties 0 and 1 , so do this
data[0].user.pictures.sizes[0].0.link
First of all you need to have colons to "pictures" and "sizes" :)
Secondly, it depends what your structure is.
for example:
if you need to use arrays as they appear in your example:
var a = {
"data": [
{
"user": {
"pictures": {
"sizes": [
{
0: {
"link": "http://www"
}
},
{
1: {
"link": "http://"
}
}
]
}
}
}
]
}
console.log(a.data[0].user.pictures.sizes[0][0].link);
or you just need a json without arrays in it:
var b = {
"data": {
"user": {
"pictures": {
"sizes": {
0: {
"link": "http://www"
},
1: {
"link": "http://"
}
}
}
}
}
}
console.log(b.data.user.pictures.sizes[0].link);
or you can even mix them:
var c = {
"data": {
"user": {
"pictures": {
"sizes": [
{
"link": "http://www"
},
{
"link": "http://"
}
]
}
}
}
}
console.log(c.data.user.pictures.sizes[0].link);
notice the subtle difference of "sizes" in b and c and the double array of a. This is because json with index as keys is the same as an array. check this example:
var example = [
{
0: "example00",
1: "example01",
2: "example02"
},
{
0: "example10",
1: "example11",
2: "example12"
},
]
console.log(example[0][1]); // == example01
you can see that you have 2 arrays within the example array
hope that helps :)
Your JSON is wrong, it should be as below :
var js = {
"data": {
"user":{
"pictures":{
"sizes":[
{
"link":"http://www"
},
{
"link":"http://"
}
]
}
}
}
}
To get the value:
js.data.user.pictures.sizes[0].link

How to print normalized data in React/Redux

I have a data normalized using normalizr:
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
I save entities in reducer and I want to print them on my page.
I can do that like this:
const articles = data.entities.articles;
for (let key in articles) {
console.log( articles[key].author + ', ' + articles[key].title);
}
Is that ok in React/Redux print normalized data in JSX template like this or there is exist a better way?
UPD
I create an application using this example https://github.com/reactjs/redux/tree/master/examples/real-world but I don't understand how there a data from entities printed in JSX templates.
I am confused about a data structure because usually I used arrays but in real-world example a new for me way, where data normalized like this.
To connect your reducer with your view, you need a container. Then in your view, you can do something like in following jsfiddle.
https://jsfiddle.net/madura/g50ocwh2/
var data = {
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: ["324"]
}
},
"users": {
"1": {
"id": "1",
"name": "Paul"
},
"2": {
"id": "2",
"name": "Nicole"
}
},
"comments": {
"324": {
id: "324",
"commenter": "2"
}
}
}
};
console.log(data.entities.articles);
return ( < div > {
Object.keys(data.entities.articles).map(function(key) {
return <p key = {
key
} > {
data.entities.articles[key].title
} < /p>
})
} < /div>);
}
You will get your data as a property to your view after you connect with container. So you can access your data like below in your view.
this.props.data.entities.articles;

How to iterate through deeply nested objects inside of a JSON?

I know there are plenty of questions about iterating through JSON objects but I haven't found one that quite relates to my exact problem. This is the JSON that I'm trying to iterate through:
psinsights = {
"kind": "pagespeedonline#result",
"id": "/speed/pagespeed",
"responseCode": 200,
"title": "PageSpeed Home",
"score": 90,
"pageStats": {
"numberResources": 22,
"numberHosts": 7,
"totalRequestBytes": "2761",
"numberStaticResources": 16,
"htmlResponseBytes": "91981",
"cssResponseBytes": "37728",
"imageResponseBytes": "13909",
"javascriptResponseBytes": "247214",
"otherResponseBytes": "8804",
"numberJsResources": 6,
"numberCssResources": 2
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidBadRequests": {
"localizedRuleName": "Avoid bad requests",
"ruleImpact": 0.0
},
"MinifyJavaScript": {
"localizedRuleName": "Minify JavaScript",
"ruleImpact": 0.1417,
"urlBlocks": [
{
"header": {
"format": "Minifying the following JavaScript resources could reduce their size by $1 ($2% reduction).",
"args": [
{
"type": "BYTES",
"value": "1.3KiB"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
},
"urls": [
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://code.google.com/js/codesite_tail.pack.04102009.js"
},
{
"type": "BYTES",
"value": "717B"
},
{
"type": "INT_LITERAL",
"value": "1"
}
]
}
},
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://www.gmodules.com/ig/proxy?url\u003dhttp%3A%2F%2Fjqueryjs.googlecode.com%2Ffiles%2Fjquery-1.2.6.min.js"
},
{
"type": "BYTES",
"value": "258B"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
}
}
]
}
]
},
"SpriteImages": {
"localizedRuleName": "Combine images into CSS sprites",
"ruleImpact": 0.0
}
}
},
"version": {
"major": 1,
"minor": 11
}
};
Now, I'm trying to write a function that iterates through all of the ruleResults objects and returns an array of the localizedRuleName properties. According to the JSON, ruleResults has three member objects (AvoidBadRequests, MinifyJavaScript, and SpriteImages). Each of these has a localizedRuleName property I'm trying to access, but when I print out my array, it's blank. Here's how I've written my function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
}
return ruleArray;
}
console.log(ruleList(psinsights));
Can you guys help me get on the right track? I used basically this same method to iterate through the pageStats of the JSON and it worked perfectly. I'm not sure why I can't get it to work with these deeper nested objects and properties.
your problem is not your iteration, but your undefined variable "counter".
Instead of using a counter can use the "push" function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray.push(results.formattedResults.ruleResults[ruleName].localizedRuleName);
}
return ruleArray;
}
fiddle: https://jsfiddle.net/fo9h56gh/
Hope this helps.
you're probably getting a javascript error since counter is not defined. you can try this:
function ruleList(results) {
var ruleArray = [];
var counter = 0;
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
counter++;
}
return ruleArray;
}

Categories

Resources