set json property depending on child property - javascript

I am creating this JSON object
{
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"image_aspect_ratio": "square"
"elements": [
new CreateBallon(results[rand])
]
}
}
}
I want to set the image_aspect_ratio in only if elements[0].someProp is present.
How can I do that?

Let's clear what JSON is. It is a textual notation for data. If you do anything with the object that involves code of Javascript don't call it JSON so, The object you're talking about is not a JSON but a JavaScript object created via object literal notation.
Now to answer your query, you can't refer to this object before you've fully initialized that object. So what you can do is initialize your object with some default value and then you should be able to edit any property based on the properties from the same object. Something like
var obj = {"property1" : "X", "property2" : ""};
Now you can update your object like
obj.property2 = obj.property1 =='yourCondition' ? 'NewValue' : obj.property2

Related

Embedded Objects to Arrays

I was given an existing project where the data structure is below:
[
{
"key": "username",
"value": ""
},
{
"key": "password",
"value": ""
},
{
"key": "cars",
"value": [
{"ABC-1234-1234": "s4LmoNzee9Xr6f7uu/"},
{"ABC-5678-5678": "s5LmoNzee9Xr5f9uu/"}
]
}
]
Cars' value is an array of objects.
To create the initial object in the cars' array, I do the following:
var encryptedStuff = json.data;
var carkey = carid;
var entry = {};
entry[carkey] = encryptedStuff;
var carArray = [];
key="cars";
carArray.push(entry);
I need to push the array into another function that turns it into a string in a stored variable.
My problem...and I'm really rusty on embedded objects...is to do the following:
1.) Get the string
2.) JSON.parse back into an object (I got this far as I'm using a jQuery grep but I'd prefer to use JavaScript).
Here's my problem...
3.) locate the cars key in the object and get its value.
4.) Turn the value into an array to either delete an item or to add one (as per the code above where I'm writing the object into the array.
In the case of adding, I would have to copy the cars' value into the carArray[] and then push the new item into it.
In the case of deleting, I would have to remove the item and push back everything back into the carArray[].
I would do things differently but I can't change the structure of the data as this is approved company-wide.
Any help would be appreciated.
Thanks
You don't need to make a copy of the car's value array to add new entries nor make a copy then "push back" to remove an entry - you can reference it directly in the parsed object.
You can use
JSON.parse
array.find
array.push
array.splice
JSON.stringify
Giving:
var source = `[
{
"key": "username",
"value": ""
},
{
"key": "password",
"value": ""
},
{
"key": "cars",
"value": [
{"ABC-1234-1234": "s4LmoNzee9Xr6f7uu/"},
{"ABC-5678-5678": "s5LmoNzee9Xr5f9uu/"}
]
}
]`
// convert json to an object
var data = JSON.parse(source);
console.log(data, data.find(e=>e.key=="cars").value)
// add an item to the cars.value
data.find(e=>e.key=="cars").value.push({"ABC-": "s6..." });
// remove an item from the cars.value
data.find(e=>e.key=="cars").value.splice(1,1);
// confirm items added/removed
console.log(data, data.find(e=>e.key=="cars").value)
// convert back to a strng to send back to the service
var result = JSON.stringify(data);
console.log(result);

Access items inside of an array of objects

I have a rather simple JSON file that I'm trying to access the items inside of. I had this working but for some reason it no longer works and it is making my brain hurt. Here is the JSON:
[
{
"firstItem":
{
"message": "firstItem is working",
"value": ["hello", "world"]
}
},
{
"secondItem":
{
"message": "secondItem is working",
"value": ["hello", "aliens"]
}
}
]
Note that there is an array of two objects (firstItem and secondItem) which have objects within them (message and value). I am trying to access these items like so:
// the json from above is equal to json
json.map(items => {
console.log(items.firstItem.message)
console.log(items.firstItem.value.join(", "))
console.log(items.secondItem.message)
console.log(items.secondItem.value.join(", "))
})
As always, any help would be appreciated.
Edit: I put the closing parenthesis on the joins. This was not part of my issue. I guess I'm too used to VSCode doing it for me. :)
You were missing a closing parentheses on your console.log join statements. The second and larger problem was that with map you are looping through firstItem first and then secondItem, so in the first iteration map doesn't know what secondItem is. I changed the names of each object to "item" and halved the code inside map to solve the problem:
const json = [
{
"item":
{
"message": "firstItem is working",
"value": ["hello", "world"]
}
},
{
"item":
{
"message": "secondItem is working",
"value": ["hello", "aliens"]
}
}
]
json.map(items => {
console.log(items.item.message);
console.log(items.item.value.join(", "));
})
Note that there is an array of two objects (firstItem and secondItem) which have objects within them (message and value). I am trying to access these items like so:
The example you show, shows an array containing two objects, where the first object has a property called firstItem and the second property has a property called secondItem. The properties in both the objects are objects themselves and both have two properties called message and value.
I hope that makes sense.

Accessing data from json in Angularjs

I have a JSON object Like this-
[
{
"user": "A220",
"shorttext": "shanghai",
"reportedBy": "S,A",
"questions": "
[{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"w\",\"ansYesOrNo\":false,\"ansDetails\":\"\"},{\"question\":\"Q2\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"ed\",\"ansYesOrNo\":false,\"ansDetails\":\"\"}]",
"notifno": "20143995",
"error": "",
"createdOn": "2015-09-09 13:08:36",
"Id": 0,
"$$hashKey": "object:89"
}
]
I need to access the 1st question of questions.Please i am not able to access it like this alert(obj.questions[0].question);
Here is a jsFiddle Link-LINK to Fiddle
The main problem is that the questions array inside the object, It is not an array. Is a Array convert to string, you must parse the questions to get the respective Json object with the data.
Here is your fiddle updated: http://jsfiddle.net/marduke182/w02ck9uw/1/
And the part of code important:
var questonObj = JSON.parse($scope.a[0].questions);
Use fromJson method this way:
angular.fromJson(a[0].questions)[0].question

How to get the name of the array in json data using JavaScript

I have a JSON object which comes back like this from a JavaScript API call:
{
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
How can I access the name of the array (i.e myArray) in JavaScript. I need to use the name of the array to determine the flow later on.
Use getOwnPropertyNames to get a list of the properties of the object in array form.
Example:
var myObj = {
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
},
names = Object.getOwnPropertyNames(myObj);
alert(names[0]); // alerts "myArray"
Note: If the object can have more than one property, like myArray, myInt, and myOtherArray, then you will need to loop over the results of getOwnPropertyNames. You would also need to do type-testing, as in if(names[0] instanceof Array) {...} to check the property type. Based on your example in your question, I have not fleshed all of that out here.
Object.keys(data)[0]
# => "myArray"
A terminology note: This solution assumes you have a JavaScript object. You might have a JSON string, in which case this is the solution:
Object.keys(JSON.parse(data))[0]
# => "myArray"
However, "JSON object", in JavaScript, is just one - the one I used just now, that has JSON.parse and JSON.stringify methods. What you have is not a JSON object except perhaps in a trivial interpretation of the second case, where all values in JavaScript are objects, including strings.
The other answers are good if you have no control over the return format.
However, if you can, I'd recommend changing the return format to put the important values you care about as actual values instead of keys to make it clearer. For example, something like this:
result =
{
"name: "myArray",
"value": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
Then, it's a lot clearer to reliably access the property you care about: result.name

jquery mobile javascript verify json key

My mobile app reads an external json object. How can I check in javascript that a key node exists in the dynamically generated json structure? I tried the hasOwnProperty or containsKey methods, but without luck.
Example json data:
{ "element1":
{ "element2": { "Number": "0" },
"element3": { "Number": "1" },
"element4": { "Number": "2" }
}
}
As these elements are generated dynamically, I want to check if the key element3 exists in this structure. No luck with data.element1.hasOwnProperty("element3").
Yes, hasOwnProperty() method does not work for a Json object. It works for a Java Script Object. So You just need to convert this Json object into a Java Script Object using eval() method and check inside that object.
When you convert above Json structure, it will create an Object (element1) inside another Object (say JSObject). element1 will contain properties element2, element3 and element4. So your code should go like this.
var MyObject={ "element1":
{ "element2": { "Number": "0" },
"element3": { "Number": "1" },
"element4": { "Number": "2" }
}
}
var JSObject=eval('(' + MyObject+ ')');
var IsExistElement3 = JSObject.element1.hasOwnProperty("element3");

Categories