Can't get data from JavaScript array - javascript

I have this code
var obj = [];
$('#next').click(function(){
jQuery.getJSON(produk1 , function(product1) {
hargana1 = product1.price;
obj.push({
harga: hargana1
});
}
jQuery.getJSON(produk2 , function(product1) {
hargana2 = product2.price;
obj.push({
harga: hargana2
});
}
console.log(harga)
});
And I have result on my console like this
How can I get value from harga?
I try with obj['harga'] It shows undefined

Well if you take a closer look then you will see that this is actually an array filled with objects. you can see that its an array by the brackets []
Try it like this: obj[0].harga

You should iterate through the array :
const out = [{harga:21132424},{harga:543535}]
console.log(out)
out.forEach(obj=>{
const harga = obj.harga;
//do something to harga here
console.log(harga)
})

Related

Getting Multiple unorganized values from JSON in Javascript

I have the following javascript
{
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"
[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1},
{\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
What I am trying to do is, to use javascript to get the TagName from Tags section
When i use JSON.parse(Obj.Tags); I get everything under Tags section where i only want TagName
Is it possible?
It's possible. You can use the .map function.
var tagNames = obj.Tags.map(function(x){
return x.TagName;
});
var obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":
[{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}]
};
var tagNames = obj.Tags.map(function(x){
return x.TagName;
})
console.log(tagNames)
I think I probably get what your question is.
Would you like your Tags to be only array of TagName?
Here's example code:
var Obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
// Get Tags data to array object
var Tags = JSON.parse(Obj.Tags);
// Get simple array of TagNames
var TagNames = Tags.map(x=>x.TagName);
console.log(TagNames);
// Get array of objects with only TagName key value pair
var TagNamesFormat2 = Tags.map(function(x){
return {"TagName" : x.TagName}
});
console.log(TagNamesFormat2);
You can use map() on Tags
// Parsed object
var data = {
"Exists": true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,
"Fav":false,
"Shield":false,
"Tags": [
{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}
]
}
console.log(data.Tags.map(tag => tag.TagName));
Try tags.map(a => a.TagName);
var myObj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
};
var tags = JSON.parse(myObj.Tags);
var tagNames = tags.map(a => a.TagName);
console.log(tagNames);

How to show correct value using JSON.parse()?

I have JSON code which I want to parse but it is not parsing as I expected. I need to show only messages but it is showing me extra information like Object, Array. How to fix it?
var txt = "";
var json_string = JSON.stringify(data.json_data);
var json_object = JSON.parse(json_string, function(key, value){
txt += value;
});
console.log(txt);
Message in browser console:
Enter the same password as above, for verification. crud.js:45:25
Array [ <1 empty item> ] crud.js:45:25 <-- DONT NEED TO SHOW
Email already exists. crud.js:45:25
Array [ <1 empty item> ] crud.js:45:25 <-- DONT NEED TO SHOW
Object { } <-- DONT NEED TO SHOW
I have got solution for you. Please check below code.
var data = {
'json_data' : {
'test1' : 'test1',
'test2' : 'test2',
}
}
var json_string = JSON.stringify(data.json_data);
console.log(jQuery.parseJSON(json_string));
var json_object = jQuery.parseJSON(json_string);
$.each(json_object,function(index, value) {
console.log(index);
console.log(value);
});
It will work.
Please check below link as well
https://jsfiddle.net/bnsk9pe7/

How do I get items from localStorage?

In my app I've got 2 functions to work with localStorage.
When I add the first and second items, it works properly, but when it is the third item, it gives an error.
Here are the functions:
w.getLocalStorage = function() {
var c = localStorage.getItem('cities');
var arr = [];
arr.push(c);
return c ? arr : [];
}
w.setLocalStorage = function(data, googleData, cities, name) {
if (data) {
city.name = data.name;
city.coord.lat = data.coord.lat;
city.coord.lon = data.coord.lon;
cities.push(JSON.stringify(city));
// console.log(city);
localStorage.setItem("cities", cities);
} else if (googleData) {
city.name = name;
city.coord.lat = googleData.results[0].geometry.location.lat;
city.coord.lon = googleData.results[0].geometry.location.lng;
console.log('cities', cities);
cities.push(JSON.stringify(city));
// console.log(cities, city);
localStorage.setItem("cities", cities);
}
}
Here is what it returns for the first 2 items:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
Here is what when the third items is added:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}, {"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
How can I fix this?
As you can only store string in localStorage, to persist object convert them in stringified format using JSON.stringify() method and on retrieval use JSON.parse() to parses the JSON string to construct the JavaScript value or object.
Here are the code snippet, which require attention. You should persist stringified cities data
cities.push(city);
localStorage.setItem("cities", JSON.stringify(cities));
While retrieval, parse it JavaScript object
var cities = localStorage.getItem('cities');
var c = cities ? JSON.parse(cities) || [];

Array push behavior

Although I have some basic JavaScript background, I stumbled upon this code that I wrote:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var tempArr=[];
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
In the final loop, I expected table to contain the arrays for Tom, Pat, and Sam . Instead, this is what I got:
table[["Tom","Moody","Tom#example.com",30]]
table[["Pat","Smith","pat#example.com",32],["Pat","Smith","pat#example.com",32]]
table[["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28]]
table[["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28]]
Why is push() replacing the previous entry in table? Any help will be highly appreciated.
The others already pointed out problems in your code.
However, you also make things more complicated than necessary. You can just do this:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}];
var table = data.map(function(user) {
return [
user.fName,
user.lName,
user.email,
user.age,
];
});
console.log(table);
Or if you use ES6:
var table = data.map(user => [ user.fName, user.lName, user.email, user.age ];
You don't need to write all the boilerplate code by hand. Use a proper array iterator (map in your case).
var table = data.map(function(user) {
return [user.fName, user.lName, user.email, user.age];
});
Obviously map isthe way to go for the sake of functional approach however if you like imperative styles one simplistic way could be using for of loop as follows.
var data = [{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}],
table = [];
for (var user of data) table.push([user.fName,user.lName,user.email,user.age]);
console.log(table);
Problem here is not with push. Variable in javascript store reference to array. And in table you are pushing reference to same array tempArr. You need to create new array before pushing it or create deep copy of array before pushing it.
Example
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
var tempArr=[];
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
Well, unlike a lot of other languages, JavaScript has passes everything by reference. That means that when you table.push(tempArr);, you're not actually pushing the values of tempArr, you're pushing a reference to tempArr. So, if you do this:
var a = 'a';
var table = [];
table.push(a);
a = 'b';
console.log(table[0]);
You'll get b as your output. What you want to do is define a new variable to push, like this
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
var tempArr=[];
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
});
console.log('table'+JSON.stringify(table));
var data = [{"_id": "57b3e7ec9b209674f1459f36","fName": "Tom","lName": "Moody","email": "Tom#example.com","age": 30}, {"_id": "57b3e8079b209674f1459f37","fName": "Pat","lName": "Smith","email": "pat#example.com","age": 32}, {"_id": "57b3e8209b209674f1459f38","fName": "Sam","lName": "Dawn","email": "sam#example.com","age": 28}, {"_id": "57b3e8219b209674f1459f39","fName": "Sam","lName": "Dawn","email": "sam#example.com","age": 28}],
table = [];
data.forEach(function(user) {
table.push([user.fName, user.lName, user.email, user.age]);
});
console.log(table);

How to get JSON Data depending on other data values in JavaScript

My Json is like this:
[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
]
I want all the names which have BankOut value as "Y" into an array using JavaScript, in order to use those names in my protractor automation.
You need to use filter method of array. It takes function as it argument. And runs it against each element of array. If function returns true (or other truthy value) then that element stays in newly created array.
var list =[ {"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var onlyBankOutY = list.filter(function (item) {
return item.BankOut === 'Y';
});
document.body.innerHTML = onlyBankOutY.map(function (item) {
return JSON.stringify(item);
}).join('<br>');
var list =[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null}, {"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var names = [];
list.forEach(function(el) {
if (el.BankOut === 'Y') {
names.push(el.name)
}
})

Categories

Resources