I had an array like this
var data = [
{
name:"Movies",
info: "category_name",
data: [
{
name:"Interstellar",
info: "category_data"
},
{
name:"Dark Knight",
info: "category_data"
},
]
},
{
name:"Music",
info: "category_name",
data: [
{
name:" Adams",
info: "category_data"
},
{
name:"Nirvana",
info: "category_data"
},
]
}
]
console.log(data[0]);
If I console.log ([1][0]) the answer is undefined. I want to show "Interstellar" or "category data". Which is the index of this array?
data[1][0] is undefined because data[1] is will give you the second object in the array, data[1][0] wont give you the first value in data[1], instead, data[1].name will be the first value in your object. The square brackets with index are only applicable to arrays
Related
I am having trouble effectively identifying/replacing the value I need inside an Object for an editing pay rates application.
{
Physicians: {
telehealth: {
orgName: "ORG B",
weekdayEncounters: { type: "each", value: 15 },
weeknightEncounters: { type: "each", value: 16.25 },
weekendDayEncounters: { type: "each", value: 16.25 },
weekendNightEncounters: { type: "each", value: 17.25 },
holidayEncounters: { type: "each", value: 17.25 },
stipend: { type: "lump", value: 0 },
},
},
NonPhysicians: {
telehealth: {
orgName: "ORG B",
weekdayEncounters: { type: "each", value: 15 },
weeknightEncounters: { type: "each", value: 16.25 },
weekendDayEncounters: { type: "each", value: 16.25 },
weekendNightEncounters: { type: "each", value: 17.25 },
holidayEncounters: { type: "each", value: 17.25 },
stipend: { type: "lump", value: 0 },
},
},
date: "07-2021",
orgName: "ORG B",
ltc: false,
}
I am looking to replace the value inside the deepest object depending on the field that is edited. At this point I just keep getting messier and messier code trying to dig into the object read it and then replace the correct value. I have an example in written up here. Please take it easy on me I am still learning. Advice would be greatly appreciated.My issue currenlty is that I am returning an array full of undefineds and then the one object I need. Thanks in advance.
I went into your example and took the top level object 'NEWRATES'. The example code below goes through each of the sub-object NEWRATES['ltc'][0]['Infinity']['Physicians']['associates'], and prints the value under the key 'value'. It also does a quick check for the type since the lowest level contains some keys that map to strings, e.g. (orgName: "Infinity").
The Object.entries function call is necessary to make the indicated object NEWRATES[...] iterable.
for( let [key,value] of Object.entries(NEWRATES["ltc"][0]['Infinity']['Physicians']['associates']) ){
if(typeof value == "object"){
console.log('value is: ' + value.value);
}
}
This should be enough to get you going again. Simply replace the top level keys from 'ltc' -> 'standard' , 'Physicians' -> 'NonPhysicians' to iterate through the other portions of the top level object.
I want to fetch all the names and label from JSON without loop. Is there a way to fetch with any filter method?
"sections": [
{
"id": "62ee1779",
"name": "Drinks",
"items": [
{
"id": "1902b625",
"name": "Cold Brew",
"optionSets": [
{
"id": "45f2a845-c83b-49c2-90ae-a227dfb7c513",
"label": "Choose a size",
},
{
"id": "af171c34-4ca8-4374-82bf-a418396e375c",
"label": "Additional Toppings",
},
],
},
]
}
When you say "without loops" I take it as without For Loops. because any kind of traversal of arrays, let alone nested traversal, involve iterating.
You can use the reduce method to have it done for you internally and give you the format you need.
Try this :
const data = {
sections: [
{
id: "62ee1779",
name: "Drinks",
items: [
{
id: "1902b625",
name: "Cold Brew",
optionSets: [
{
id: "45f2a845-c83b-49c2-90ae-a227dfb7c513",
label: "Choose a size"
},
{
id: "af171c34-4ca8-4374-82bf-a418396e375c",
label: "Additional Toppings"
}
]
}
]
}
]
};
x = data.sections.reduce((acc, ele) => {
acc.push(ele.name);
otherName = ele.items.reduce((acc2, elem2) => {
acc2.push(elem2.name);
label = elem2.optionSets.reduce((acc3, elem3) => {
acc3.push(elem3.label);
return acc3;
}, []);
return acc2.concat(label);
}, []);
return acc.concat(otherName);
}, []);
console.log(x);
Go ahead and press run snippet to see if this matches your desired output.
For More on info reduce method
In the context of cJSON
yes, we can fetch the key value for any of the object.
1 - each key value is pointed by one of the objects. will simply fetch that object and from there will get the key value.
In the above case for
pre-requisition: root must contain the json format and root must be the cJSON pointer. if not we can define it and use cJSON_Parse() to parse the json.
1st name object is "sections" will use
cJSON *test = cJSON_GetObjectItem(root, "sections");
char *name1 = cJSON_GetObjectItem(test, "name" )->valuestring;
2nd name key value
cJSON *test2 = cJSON_GetObjectItem(test, "items");
char *name2 = cJSON_GetObjectItem(tes2, "name")->valuestring;
likewise, we can do for others as well to fetch the key value.
I am storing a java script object in the DB by converting that into the string by using JSON.stringify, But when i want to retrieve that object from DB i use the JSON.parse. But the JSON.parse is not returning the original object. In the below console screenshot it can be seen that the object Obj had some changes after it is converted into string and then parsed. So how can i get back the original object after doing JSON.stringify
The Object is as below:
var Obj = {
onchange: function(){
},
validate: function(obj){
},
elements: {
"list": {
menu: [{
caption: "Append an",
action: Xonomy.newElementChild,
actionParameter: "dd"
}]
},
"item": {
menu: [{
caption: "Add ",
action: Xonomy.newAttribute,
actionParameter: {name: "label", value: "something"},
hideIf: function(jsElement){
return jsElement.hasAttribute("label");
}
}, {
caption: "Delete this ",
action: Xonomy.deleteElement
}, {
caption: "New before this",
action: Xonomy.newElementBefore,
actionParameter: "sas"
}, {
caption: "New after this",
action: Xonomy.newElementAfter,
actionParameter: "aa"
}],
canDropTo: ["list"],
attributes: {
"label": {
asker: Xonomy.askString,
menu: [{
caption: "Delete this",
action: Xonomy.deleteAttribute
}]
}
}
}
}
};
As already mentioned in comments - you can't serialize JS functions with JSON.stringify. Please take a look at serialize-javascript library to store the functions.
I am looking to rename a variable with a different name depending on its level within a nested JSON dataset.
An example JSON file is the following:
[
{
key: "John Doe School",
values: [
{
key: "Mr. Brown",
values: [
{
key: "Joe",
TestScore: 95
},
{
key: "Sarah",
TestScore: 99
}
]
}
]
}
]
In this example, I would like to change the first-level "key" to "School", the second-level "key" to "Teacher", and the third-level "key" to "Student".
The JSON dataset would look like this following the changes:
[
{
School: "John Doe School",
values: [
{
Teacher: "Mr. Brown",
values: [
{
Student: "Joe",
TestScore: 95
},
{
Student: "Sarah",
TestScore: 99
}
]
}
]
}
]
Well, given your example, you could just do this...
var json = [
{
key: "John Doe School",
values: [
{
key: "Mr. Brown",
values: [
{
key: "Joe",
TestScore: 95
},
{
key: "Sarah",
TestScore: 99
}
]
}
]
}
];
json[0].key = "School";
json[0].values[0].key = "Teacher";
json[0].values[0].values[0].key = "Student";
json[0].values[0].values[1].key = "Student";
UPDATE FOLLOWING COMMENT
json[0]['School'] = json[0].key; // Add new key:value
delete json[0].key; // Delete previous one
json[0].values[0]['Teacher'] = json[0].values[0].key; // Add new key:value
delete json[0].values[0].key; // Delete previous one
json[0].values[0].values[0]['Student'] = json[0].values[0].values[0].key; // Add new key:value
delete json[0].values[0].values[0].key; // Delete previous one
json[0].values[0].values[1]['Student'] = json[0].values[0].values[1].key; // Add new key:value
delete json[0].values[0].values[1].key; // Delete previous one
I assume you will be looping through a number of different JSON objects however, so you would of course also need to implement that but the above structure should point you in the right direction ;)
I have an array like this:
message_list = [
{
"Main_body": "test msg",
"emp_name": "test",
"emp_salary": "5000 USD"
}
]
Its length (e.g., message_list.length) is 1.
Now I have another array like this:
added_user_data = [
{
"PostSharedLog": {
userids: "2,4,5"
},
"created": "2123123"
},
{
"PostSharedLog": {
userids: "3,1"
},
"created": "2123147"
}
]
Its length (added_user_data.length) is 2.
I want to push the above array added_user_data into message_list.
I tried doing it inside a for loop, now since the length of message_list is 1, for the second iteration, the values do not get pushed since message_list[1] does not exist and is undefined. But I still want to create message_list[1] even if it does not exist.
if i do the below :
for(var k =0;<count(added_user_data.length);k++)
{
message_list[k].PostSharedLog = added_user_data[k].PostSharedLog ;
}
It only appends the first row from the array added_user_data and gives an output like this when i print out message_list :
[{
"Main_body": "test msg",
"emp_name": "test",
"emp_salary": "5000 USD",
"PostSharedLog": {
userids: "2,4,5"
} }]
The second iteration does not append anything at all .
I would like to see the below :
[{
"Main_body": "test msg",
"emp_name": "test",
"emp_salary": "5000 USD",
"PostSharedLog": {
userids: "2,4,5"
},
"PostSharedLog": {
userids: "3,1"
}
}]
JSON objects can not have duplicate keys.
A JSON object is basically a Map it has keys and values. Each key in an object must be unique.
Invalid JSON
What you posted as your desired outcome can never exist because PostSharedLog can only exist once. Setting it again just changes the value.
Also userids is not a valid JSON key, it should be wrapped with " always!
Any JSON linter will show you exactly why this is.
{
"Main_body": "test msg",
"emp_name": "test",
"emp_salary": "5000 USD",
"PostSharedLog": {
userids: "2,4,5"
},
"PostSharedLog": {
userids: "3,1"
}
}
What you probably need to do is something like:
{
"MainBody": "test msg",
"EmployeeName": "test",
"EmployeeSalary": { "amount": 5000, "currency": "USD" },
"PostSharedLog": {
"UserIds": [2,4,5,3,1]
}
}
NOTES:
Your names are not consistent. Really? Every one of them is a different format?
Do not abbreviate.
Do not store multivalue fields in String types, use a real Array! [1,2,3,4] instead of "1,2,3,4"
Do not store mutlivalue fields in String types, use a real Object! { amount: 5000, currency: "USD" } instead of "5000 USD"