I have json array from Json object in js like :
let jsonObject = JSON.parse(response);
let jsonArray = jsonObject.items;
When I'm trying to parse it as array using
jsonArray.map((item)=>{
console.warn(item.name); // also I tried with for loop like jsonArray[i].name
})
I got error like TypeError: Cannot read property.
But in jsonArray I have element with key name. Also when I'm trying print as jsonArray[0].name it works fine!
Example of jsonArray (Json objects on jsonArray is not same):
[
{
"name":"SomeNameHere",
"secondKey":"secondValue"
},
{
"type":"typeValue",
"secondType":"typeValue",
},
{
"name":"SomeNameHere",
"secondKey":"secondValue"
},
{
"type":"typeValue",
"secondType":"typeValue",
}
]
If it important I used Mac OS Mojave, and running react-native run-android on my device
viewListArray = jsonArr.map((item) => {
console.warn(item.name);
});
jsonArray.forEach((item) => {
console.warn(item.name);
});
Array.forEach() will loop through an array.
on each second JSON object I don't have property name "name". and I did't check it. Now I'm checking like item.name == undefined?item.name:'';
Related
I am new to node and I am trying to fetch name from the obj but the problem is
How to fetch data from inner json object as my json object look like this
let obj=
{
"h4354desdfqw":{
name:"Computer",
os:"Window",
},
"hjsado24334":{
name:"Software",
type:"Adobe",
},
"qwsak032142":{
name:"hardware",
type:"hardisk",
},
}
console.log(obj.h4354desdfqw.name)
I am trying to fetch all the name which are present inside the json object
like this
computer
Software
hardware
I am not sure in which representation you would like get the data. I can assume - you would like to get array of the names
let obj=
{
"h4354desdfqw":{
name:"Computer",
os:"Window",
},
"hjsado24334":{
name:"Software",
type:"Adobe",
},
"qwsak032142":{
name:"hardware",
type:"hardisk",
},
}
const result = Object.values(obj).map(i => i.name);
console.log(result)
Object.values(obj).map(i => console.log(i.name));
You want to get the value of name for each object.
So let's iterate through each object's name with the map function :
const result = Object.values(obj).map(i => i.name);
console.log(result);
[
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]
Above is my JSON Array that is stringified,I tried to JSON.parse and other functions like iterating it in a for loop but the key values also got scrambled.
Is there any way or an npm method that could instantly output the retrieved variable?
var cartItemFromLocalStorage = JSON.parse(localStorage.getItem("cartitem"));
if (cartItemFromLocalStorage != null) {
console.log("It came defined");
console.log("This is OG Array: " + cartItemFromLocalStorage);
let cartItemObject = {
//set object data
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemFromLocalStorage.push(cartItemObject);
localStorage.setItem("cartitem", result); //localstorage only supports strings
toast.success("Item Added to cart");
}
I checked the consoles and the states are putting up the data correctly.
I'm an extreme beginner in react js, help is much appreciated
The "JSON" you have written is actually JavaScript, not JSON. To convert it JSON use the JSON.stringify function, like so
> JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]);
'[{"comicid":"5f55e91271b808206c132d7c","purchasetype":"pb_single"}]'
and then replace the value in localStorage with it.
Even easier would be to type into the developer console
localStorage.setItem("cartitem", JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]));
I try to to get a value form json object.
var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"DEF"}]
};
Object.keys(data).forEach(function(element, key, _array) {
console.log("branchId: "+element+" "+"BranchName : "+data[element][key].branchName)
for(dept of data[element]) {
console.log("Department name : "+dept.departmentName)
}
});
Here output is : the first result only and throws branchName is undefined exception.
But if the json object has multi object,its working fine.
var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"XYZ"},
{"departmentID":3,"departmentName":"Food","branchId":2,"branchName":"XYZ"}]
}
I think, since I'm new to javascript, I couldn't solve. I tried a lot of reference to solve this problem, but I could not. Please try to solve this. Thanks in advance.
he first result only and throws branchName is undefined exception.
You need to replace
data[element][key].branchName
with
data[element][0].branchName
Because
element is the key "1",
so data[element] becomes [{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
data[element][0] becomes {"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}
finally data[element][0].branchName is "ABC"
You have something mixed with your keys and indexes.
You can use Object.values (ES8 only) to get exact the values and left the keys part. Then iterate over them and make your strings.
const data = {
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"DEF"}]
}
Object.values(data).forEach(function(values) {
values.forEach(value => {
console.log(`branchId: ${value.branchId} BranchName: ${value.branchName} Department Name: ${value.departmentName}`);
});
});
I have a json like
var obj={
"address":{
"addlin1":"",
"addlin2":""
},
"name":"sam",
"score":[{"maths":"ten",
"science":"two",
"pass":false
}]
}
Now when Iam trying to modify the json iam try an array variable and passing above json to that like
var data=JSON.parse(obj);
var json={};
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];
For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]
So,when i console the json it is in this way
"name":"sam",
"address":{
"addresslin1":"",
"addresslin2":""
},
"score":{}
}
So how can I also read the values inside [] array.
Can someone help me
Thanks
json['maths']=data['score'][0]['maths'];
if you're not sure that data['score'] has any elements you can check prior to reading maths key:
if (data['score'].length) {
json['maths']=data['score'][0]['maths'];
}
data['score'] is an array, so you can't read it like that
json['maths']=data['score']['maths'];
you have to read it like that:
json['maths'] = data['score'][0].maths;
Also, obj is not a JSON, but a JavaScript object. You can use it directly.
json['maths'] = obj['score'][0].maths;
A JSON is a string, like that:
JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";
create another json2 to contain score data then assign to json.
for example :
var json={};
json2 = {}
json2[0] = 1;
json2[1] = 2;
json[0] = json2;
i try to build json structure object dynamically according examples i saw in the net but with no success.
this is the json i try to build:
{
"campaigns": [
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
},
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
}
]
}
and this is the code :
this function called each time there is data to build the campaigns (in the json) element
var campaignsJson ={};
campaignsJson.campaigns =[];
var i = 0;
function buildJson(stateCampaignId,
profile_id,
stateSelectedValue,
dailyImpressionGoalValue,
pacingValue,
segmentGroupTargetsUpdatedataValue,
frequencytypeProfileValue,
frequencysetProfileValue
)
{
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
campaignsJson.campaigns[i].profile_id = profile_id;
campaignsJson.campaigns[i].state = stateSelectedValue;
campaignsJson.campaigns[i].goal = dailyImpressionGoalValue;
i++;
var campaignsJsonstringify = JSON.stringify(campaignsJson);
alert(campaignsJsonstringify);
}
it gives me "cannot set property campaign_id of undefined"
what does it means ?and why ?
Just before
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
add this :
campaignsJson.campaigns[i] = {};
So that there is an object onto which you'll be able to set properties.
Now, please, don't speak of "JSON structure". What you build is a plain standard JavaScript object while JSON is only the string based exchange format.