Looping through a JavaScript object - javascript

I'm trying to loop through this JavaScript object but it's only returning the last key.
Here's my code
var array = [
{
"outfit": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£20"
}
},
{
"outfit": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£720"
}
},
{
"outfit": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£9920"
}
}
];
for(var i=0; i<array.length; i++){
console.log(array[i]);
$('.slide .content').each(function(index){
if(i == index) {
console.log(i + "==" + index);
var contentDiv = $('.slide .content')[index];
contentDiv.innerHTML = "";
contentDiv.innerHTML = ''+ array[i].title + '<span>'+ array[i].price +'</span>'
}
});
}
I'm basically trying to loop through the data, extracting it for a look-book carousel. Then append each piece of data in $('.slide .content') for each slide of the carousel.
Any help would greatly be appreciated. Many thanks

Edited
var array = [
{
"outfit": [
{
"link": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£20"
},
},
{
"link": {
"url": "http://www.bbc.co.uk",
"title":"Trousers",
"price":"£60"
}
}
]
},
{
"outfit": [
{
"link": {
"url": "http://www.nintendo.co.uk",
"title":"Dress",
"price":"£920"
}
}
]
}
];
array.forEach(function(value, index ){
value.outfit.forEach(function( outfitValue, outfitIndex){
console.log(outfitValue.link.title);
});
});
Result
T-shirt
Trousers
Dress
https://jsfiddle.net/jzpL8dnm/13/
I changed the structure of your code. It may help you to solve your problem.
var array = [
{
"outfit": {
"link": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£20"
},
"link": {
"url": "http://www.bbc.co.uk",
"title":"Trousers",
"price":"£60"
}
}
},
{
"outfit": {
"link": {
"url": "http://www.nintendo.co.uk",
"title":"Dress",
"price":"£920"
}
}
}
];
for(var key in array){
console.log(array[key]);
}

I found that if we are having same keys in a JavaScript object then on traversing JavaScript object by transpiler/compiler it will get the updated info of keys. So keys should be unique if you really want to achieve it Associative array are the most convenient way because indexing will help you to retrieve data either the data is duplicate or not.
second way: if you want to use only js object then create array in js object where you have same key.

You have the same keys.
Keys in JS objects must be unique.

Related

how to loop inside object array Angular

I want to display values from my json but I don't know how to do it. Is it possible to loop inside an object array ? i don't know if the keyvalue pipe can help me but I want to do without.
how to get the student2 and also the name to display it ?
thanks everyone.
json
{
"student": {
"student1": [],
"student2": [
{
"id": "123",
"name": "boot"
},
"student3": [],
]
},
"teacher": {
"teacher1": [],
"teacher2": [
{
"id": "123456",
"name": "toto"
},
]
}
}
ts.file
get(){
this.service.getAll().subscribe((data:any) => {
object.keys(data).length > 0;
})
}
Assuming your JSON object from your GET request looks like the one you posted above simply do:
get(){
this.service.getAll().subscribe((data:any) => {
data.student.forEach(element => {
for (let key in element) {
console.log(" key:", key, "value:", element[key]);
for (let val in element[key]) {
console.log(" value:", val);
}
}
});
})
}

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

Javascript or jQuery way to display random-level JSON as HTML

I would like to parse and display arbitrary-level JSON snippets as HTML. By arbitrary-level I mean there is no pre-definied structure. For example:
"CustomFields": [
{
"Main": [
{
"None": [
{
"SDOM Date": "2014-12-24"
},
{
"User Defined 31": "2009-03-02"
}
]
},
{
"Contract Data": [
{
"Status2": "Active"
},
{
"User Defined 112": "N"
}
]
}
]
}
Besides the CustomFields root element, everything under it is unpreditable. But basically there are layers of objects which are each an array of other objects, until you finally arrive at an object value. In the example above there are 4 levels. But there can be any number of them.
What I'd like is to display something like:
Main
None
SDOM Date: 2014-12-24
User Defined 31: 2009-03-02
Contract Data
Status2: Active
User Defined 112: N
Try this..
var json = {"CustomFields": [
{
"Main": [
{
"None": [
{
"SDOM Date": "2014-12-24"
},
{
"User Defined 31": "2009-03-02"
}
]
},
{
"Contract Data": [
{
"Status2": "Active"
},
{
"User Defined 112": "N"
}
]
}
]
}]};
function jsonToHtml(array){
var html = '<ul>';
for (var i=0; i<array.length; i++){
if (typeof array[i] == 'object'){
for (var j in array[i]){
var innerHTML = (typeof array[i][j]=='object')?jsonToHtml(array[i][j]):' : '+array[i][j];
html += '<li>'+j+innerHTML+'</li>';
}
}
}
html += '</ul>';
return html;
}
aaa.innerHTML = jsonToHtml(json.CustomFields);
<div id="aaa"></div>

JSON Data Fuzzy merge

I have a JSON data like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
},
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
}
}
I need to search for fuzzy data and merge. For example InvestmentsDeposits and InvestmentsDeposits$$$d need to be merged because it matches closely in name
Need to use javascript for this
For now I can make sure source data will always have $$$d at the end to merge with the target data without $$$d i.e., InvestmentDeposits.
My final merged content should be like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
"text": "newtext"
}
]
}
}
}
any help on this one?
What I have tried so far
var json0 = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
}
};
var json1 =
{
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
};
// Merge object2 into object1, recursively
$.extend( true, json0, json1 );
I am able to merge the data if i am able to split the InvestmentDeposits and InvestmentDeposits$$$d in to two distinct JSON objects but how to split and move the $$$d data in to another object? to make the jquery extend work
Use Object.keys() to find an object's keys and figure out what data to move over. You can compare the first key with the others to find matches, then remove the keys you just looked at until all of them are gone. Here's an example with a similar object.
var dat = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}, "InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
},
"NotLikeTheOthers": {
"Um": "Yeah."
}
};
var result = {}; // This will be the merged object
var keys = Object.keys(dat); // Contains keys
while(keys.length) {
var i=1;
for(; i<keys.length; i++) { // Find matches
if(keys[0] == keys[i] + '$$$d') { // Match type 1
result[keys[i]] = dat[keys[i]]; // Copy orig
for(var j in dat[keys[0]]) { // Replace values
result[keys[i]][j] = dat[keys[0]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
} else if(keys[i] == keys[0] + '$$$d') { // Reverse matched
result[keys[0]] = dat[keys[0]];
for(var j in dat[keys[i]]) {
result[keys[0]][j] = dat[keys[i]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
}
}
if(i > 0) { // Didn't find a match
result[keys[0]] = dat[keys[0]];
keys.shift();
}
}
alert(JSON.stringify(result));
Note that Object.keys() requires IE9+.

How to iterate through nested objects in a generic way

I am trying to fetch the value of the nested objects without using it's key. Like for example if I have a object like
var a = {"key" : "100"}
I don't want to use a.key, to get the result, though i have nested objects, it is becoming difficult for me to fetch the value this is what I have tried:
var Obj = [{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}},{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}}]
for(var key in Obj){
abc = Obj[key]
for(var j in abc){
def = abc[key]
}
}
So i need the values of all the objects, without using the key directly.
Maybe this helps
function getValues(array, key) {
var result = [];
array.forEach(function (a) {
a[key] && result.push(a[key]);
});
return result;
}
var array = [{ "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }, { "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }];
document.write('<pre>' + JSON.stringify(getValues(array, 'ghi'), 0, 4) + '</pre>');

Categories

Resources