Create nested Json in js - javascript

I want to create Json like this:
{
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
}
I don't know how to place none-named property in json obj and place and obj into "children".

OK, if you mean key itself is variable then you cannot create json-object in single shot,
you will have to create it using '[]' notation
var myObj = {};
myObj[myProp1] = [] //or some value or some json/map again
myObj[myProp2] = 'hi'
myProp1 and myProp2 are variables.if you can explain your problem in more detail then you will get more clear answer.

If you ask how to manipulate that JSON object, then maybe this would help.
Your original object:
var object = {
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
};
1) How to place none-named property in json obj.
Object is not array, so should assign key/value, though either or both of them were empty. You can insert using dot or like array assignment.
object.country = "Malaysia";
object[""] = "No Keys";
object["novalue"] = "";
2) How to place an obj into "children".
var aNewChild = {
"childName": "Handsome one"
};
object.children.push(aNewChild);

Related

Replace nested JavaScript Object data item with dynamically created path?

I've got this JSON data object (example):
let obj = [
{
test0: [
{testA: 'ContentA' },
{testB: 'ContenB'}
]
}
];
I'd like to replace the value of key 'testB' dynamically. I.e. I need to be able to address any item in the object and replace ist.
Here's what I am doing so far:
Therefore I programmatically generate a mixed key/index path to address the target object and it looks like this (in array form):
let path = [0,'\'test0\'',1,'\'testB\''];
In order to put this in an executable form which does the actual replacement, I convert path to JavaScript code and run it with eval. Like this:
let newText = 'ContentB';
eval(`obj[${path.join('][')}]=\'${newText}\'`);
Eval executes this code literal:
obj[0]['test0'][1]['testB'] = 'ContentB'
This works, but if possible, I'd like to know if there's an alternative way which works without using "eval".
You could use a recursive function and pass it the property path as an array of properties, like this:
function setDeepValue(obj, [prop, ...path], value) {
if (!path.length) {
obj[prop] = value;
} else {
if (!(prop in obj)) obj[prop] = {};
setDeepValue(obj[prop], path, value);
}
}
// Example:
const arr = [{
test0: [
{ testA: 'ContentA' },
{ testB: 'ContenB' }
]
}];
setDeepValue(arr, [0, "test0", 1, "testB"], "ContentB");
console.log(arr);
If you are OK with using a library, you could use Lodash, which has _.set and the more flexible _.setWith to do this.

Javascript/JSON: get name of specified object as string

I'd like to get a key name of a JSON/JavaScript object as string. Maybe this is totally easy, but i just can't figure it out.
I have this object (simplified example, there are reasons to name the keys as strings):
var obj = {
"input1": {
"type": "input",
"value": "aaa"
},
"input2": {
"type": "checkbox",
"value": "bbb"
}
}
And now i would like to do something like this:
currentInputName = getTheNameOfThisAsString(obj.input1);
console.log(currentInputName); // output should be "input1"
currentInputName = getTheNameOfThisAsString(obj.input2);
console.log(currentInputName); // now output should be "input2"
I'm trying this with Object.keys() and Object.getOwnPropertyNames(), but both return type and value to me, so they are outputting the keys of the object specified, not the object name itself.
Use Object.keys() to access keys of your object.
var obj = { "input1": { "type": "input", "value": "aaa" }, "input2": { "type": "checkbox", "value": "bbb" } };
var keys = Object.keys(obj);
console.log(keys);
I am not sure what you are trying to accomplish, but I assume that you do not know the key, and thus you are sending object.key to your method.
How about changing the method to take the object and your object.key as parameters?
You call your method like this: getTheNameOfThisAsString(obj, obj.input1);
function getTheNameOfThisAsString(obj, subObject){
var keys = Object.keys(obj);
for(var key in keys){
if(subObject.value == obj[key].value){
return key;
}
}
}
From your comments, I was wondering if you can store your sub-object like this: currItem=obj["input1"], if that is the case, you already have the key as a string, and there is no need for an explicit method.
Here is an example:
var currItemName = "input1";
var currItem=obj[currItemName];

Json iteration fails when there is one sub object

I'm converting an xml string to json using php and then posting it to a
javascript file where I try to iterate it. When the object contains more than one object, json contains an array of objects like the first sample and I can iterate using the .length function but when the object contains only 1 object an array is not being created and the .length function fails. How can I make the iteration work in both cases without knowing the object's name?
Sample 1:
{"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
Sample 2:
{"class":
{
"name":"history",
"grade":"10"
}
}
You could check length, and if it's undefined it means it's just an object, then you make it an array with just one element:
if collection.length == undefined:
collection = [collection]
# the rest of the code doesn't need to be changed
You can use for for that and you don't need length
var test = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
for (var i in test){
console.log(test[i]);
}
You can check to see if the object is an array first: Array.isArray(obj) . If it isn't then you know you don't need to iterate it.
var obj = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
if (!Array.isArray(obj)) return obj;
// else iterate it.
You have to know the data type of the variable before knowing how to use .length properly.
var dataTypeLength;
var data = {
"class":
{
"name":"history",
"grade":"10"
}
}
if (Array.isArray(data.class)) {
dataTypeLength = data.class.length;
} else {
dataTypeLength = Object.keys(data.class).length;
}
console.log(dataTypeLength);

Iterate through a json object

Here is my object
var myObject = {"HardGood":362,"Music":2};
console.log(myObject[0]); // undefined? instead of "Hardwood 362"
What am I doing wrong?
myObject is an object not an array, so using [0] will indeed be undefined.
Use myObject.HardGood or myObject.Music to get the value or that property
Code
console.log(myObject.HardGood); // will output 362
console.log(myObject.Music); // will output 2
UPDATE
var objects = [
{
"title": "HardGood"
"type": "362"
},
{
"title": "Music"
"type": "2"
}
];
console.log(objects[0].title); // output HardGood
console.log(objects[1].type); // output 2
You should call the first element in an object like this: myObject.key and your key is HardGood.
In arrays it's done like this:
var _Array = [];
_Array .push('x1'); //pushing in array
_Array .push('x2');
console.log(_Array[0]); // getting the first element in that array
Update: if you want to get it dynamically:
var myObject = {"HardGood":362,"Music":2};
for(var key in myObject){
console.log(key +':'+myObject[key]);
}
You have to access JSON object property with . Like below
var myObject = {"HardGood":362,"Music":2};
console.log(myObject.HardGood); //362
Useful links Have a look at below links to understand it better.
Javascript-property-access-dot-notation-vs-brackets
JS-dot-notation-vs-bracket-notation
MDN - OperatorsProperty_Accessors

How I can build this json object with javascript code?

{
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
I don't understand how I can create object like "ma.addEvent"
the "dot" is a problem here.
Try this
var x = {
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
If you want to access, you have to use [] notation (. notation won't work, because of dots in keys) like
console.log(x["ma.addEvents"]["ma.id"])
You might want to use a square bracket notation:
var yourObject = {};
yourObject['ma.addEvents'] = {};
...and so on. Print the ma.addEvents attribute using
console.log(yourObject['ma.addEvents'])
You can use this:
var json_string = "{\"ma\.addEvents\":{\"ma\.id\":\"my-id\",\"ma\.eventIds\":[\"eventID1\",\"eventID2\"]}}";
The code above, when parsed to json (JSON.parse), will retrieve the same object that appears on your question.
Hope this helps,
Regards,
Marcelo
var obj = {
"ma.addEvents": {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
Depends on what part you would like to add dynamically.
var obj = {};
obj["ma.addEvents"] = {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
};
obj["ma.addEvents"]["ma.eventIds"].push("someotherEvent");
Please take a look at the documentation for accessors.
ma must be defined before you create ma.addEvents etc. The syntax might look like this:
// `ma` is an object
var ma = {
// It contains an object called `addEvents`
addEvents: {
// Which contains a string `id` and an array `eventIds`
id: "my-id",
eventIds: [
"eventId1",
"eventId2"
]
}
}
To create a blank object in ma, you could use the 'dot' syntax:
ma.newObject = {};
or square bracket notation:
ma["newObject"] = {};
I'm not entirely sure what your question is, are you looking to parse that JSON or to learn Javascript object syntax?

Categories