JavaScript - Pushing JSON Object Using Value as Element Name - javascript

I'm trying to push an object inside an array with dynamic attribute name.
Let's say we have the following variables defined
myJSON = {"students" : [ {"name":"Your Name"}, {"name":"My Name"} ] };
attribName = "name";
myValue = "myValue";
parsedJSON = JSON.parse(myJSON);
parsedJSON["students"].push({attribName : myValue});
myJSON = JSON.stringfy(parsedJSON);
The example isn't working. Is there a way to push an object with dynamic attribute name?

From MDN,
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
Also note that input you has provided is object, not json
var myJSON = {
"students": [{
"name": "Your Name"
}, {
"name": "My Name"
}]
};
var attribName = "name";
var myValue = "myValue";
var obj = {};
obj[attribName] = myValue;
myJSON["students"].push(obj);
console.log(myJSON);

function(key, value, json) {
var obj = {};
obj[key] = value;
json['students'].push(obj);
return arr;
}

You can also do the modification in your code :
myJSON = {"students" : [ {"name":"Your Name"}, {"name":"My Name"} ] };
attribName = "name";
myValue = "myValue123";
myJSON["students"].push({attribName: myValue});
console.log(myJSON);

Related

Use variable as property JavaScript [duplicate]

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;

Dynamically add object in javascript array

I have json:
var obj = '{"Form":[],"Provider":[]}';
I push the data with variable value to make dynamic objects:
var pName = 'Tester';
var data = {
pName :["testing"]
};
console.log(obj['Provider'].push(data));
But that adds pName as variable name but not variable value that is Tester, i tried with +pName+ that also not works.
Returns:
{"Form":[],"Provider":[{"pName":["Testing"]}]}
Any help would be appreciated.
You must use [] syntax near the property name.It will evaluate the expression in the [] and returns the value.
See the example.Here the data's property is with the name 'Tester'.
var obj = {"Form":[],"Provider":[]};
var pName = 'Tester';
var data = {
[pName] :["testing"]
};
console.log(data.pName); // undefined
console.log(data.Tester); // OK
obj['Provider'].push(data);
console.log(obj);

Apply filter to JSON.parse() dynamically

I have the following js:
var text = '{"firstName" : "abc", "lastName" : "def", "age" : 25}';
obj = JSON.parse(text).firstName;
console.log(obj);
This prints the value corresponding to the key firstName as expected. However what I am trying to do is, I want to store the key to be fetched in a variable and use it along with JSON.parse() statement. Something like this:
var text = '{"firstName" : "abc", "lastName" : "def", "age" : 25}';
var filter = 'firstName';
obj = JSON.parse(text).filter;
console.log(filter)
console.log(obj);
This code prints 'undefined' onto the console. What am i doing wrong?
Change:
obj = JSON.parse(text).filter;
to
obj = JSON.parse(text)[filter];
There are two ways to access properties: dot notation and bracket notation.
var test = object.property; //(dot notation)
var test = object[property_name]; //(bracket notation)
The issue you are facing is that you are trying to access a property called 'filter' on your object which does not exists and therefore undefined.
When trying to access a value with a key stored in a variable, you need to use the square brackets notation.
obj.key is equivalent to obj['key'], but var x = 'key'; obj.x is not equal to obj.key.
Open your console and run this code snippet
var text = '{"firstName" : "abc", "lastName" : "def", "age" : 25}';
var filter = 'firstName';
obj = JSON.parse(text)[filter];
console.log(filter);
console.log(obj);
A simple example
var obj = { a: 'A' },
filter = 'a';
console.log( obj.a ); // outputs 'A'
console.log( obj['a'] ); // outputs 'A'
console.log( obj[filter] ); // outputs 'A'
console.log( obj.filter ); // outputs undefined, obj does not have a 'filter' property
this is trying to access an attribute called filter from the parsed JSON which doesn't exist and is therefore undefined.
Instead you want JSON.parse(text)[filter]

Node.js - JSON.parse - Add Nodes to the Result

If I parse a JSON object in Node.js like this
var datap = JSON.parse(data);
I get an hierarchical object (as visible in the debugger):
datap = object
account1 = object
name = "A"
type = "1"
account2 = object
name = "B"
type = "2"
Now I would like to add an account3 with a line like this
datap.append("account3")
and ofcourse after this
datap.account3.append({"name":"C", "type":"1"})
My Javascript knowledge is still limited, is there a possibility to do so?
Once the json is parsed you can just use in as an Object:
var datap = JSON.parse(data);
datap.account3 = { name :"C", type :"1"};

How to convert string as object's field name in javascript

I have a js object like:
obj = {
name: 'js',
age: 20
};
now i want to access name field of obj, but i can only get string 'name', so how to convert 'name' to obj's field name, then to get result like obj.name.
Thank you in advance.
You can access the properties of javascript object using the index i.e.
var obj = {
name: 'js',
age: 20
};
var isSame = (obj["name"] == obj.name)
alert(isSame);
var nameIndex = "name"; // Now you can use nameIndex as an indexor of obj to get the value of property name.
isSame = (obj[nameIndex] == obj.name)
Check example# : http://www.jsfiddle.net/W8EAr/
In Javascript, obj.name is equivalent to obj['name'], which adds the necessary indirection.
In your example:
var fieldName = 'name'
var obj = {
name: 'js',
age: 20
};
var value = obj[fieldName]; // 'js'
Not related at all, but for anyone trying to define object's field name from a string variable, you could try with:
const field = 'asdf'
const obj = {[field]: 123}
document.body.innerHTML = obj.asdf
It's quite simple, to access an object's value via a variable, you use square brackets:
var property = 'name';
var obj = {name: 'js'};
alert(obj[property]); // pops 'js'
As objects are associative arrays in javascript you can access the 'name' field as obj['name'] or obj[fieldName] where fieldName = 'name'.

Categories

Resources