dynamic setting values in javascript object(json) [duplicate] - javascript

This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 8 years ago.
I've read this existing question on stackoverflow.
My target is to set a property on a "nested Property and set a new Value (without eval!):
What i have is a dynamic string as example : “A.B.C”
And a JSON Object:
var obj ={
A: {
B: {
C: 23
C1: {}
}
}
}
Now i want to access this property and set it:
If the string has a fixed amount of properties i can just write:
obj[prop1][prop2][prop3] = 42
What would be the way to make this dynamic, so when passing “A.B” the object at B is replaced?

Something like this will work..
var str = "A.B.C";
var obj ={
A: {
B: {
C: 23,
C1: {}
}
}
};
updateObj(obj,str,10);
function updateObj(obj,str,val){
var tok = str.split(".");
var update = function(obj, index){
if (index < tok.length){
if ( !obj.hasOwnProperty(tok[index])){
obj[tok[index]] = {};
}
if (index == tok.length-1){
obj[tok[index]] = val;
}
update(obj[tok[index]],++index);
}
}
update(obj,0);
}
console.log(obj);

Related

Setter for anything in JavaScript [duplicate]

This question already has answers here:
Is it possible to implement dynamic getters/setters in JavaScript?
(5 answers)
Closed 3 years ago.
I have an object, let's call it obj, it looks like this:
const obj = {
key: "value"
}
Now I want to do something when a property is set. I heard about setters,
that I can use by doing:
const obj = {
set key(e) {
console.log("Property key has been set!")
}
}
But I want to do this, for any property... Like instead of only for key, it would be for anything, example:
obj.SomeKey = "value"
Should log "Property key has been set!"
and it would be the same for any property...
Is there a way in JavaScript to do this? Thanks
You could create a ES6 Proxy, which allows you to modify the set method like so:
const obj = {
key: "value"
};
const objProxy = new Proxy(obj, {
set: (obj, prop, v) => {
obj[prop] = v;
console.log("do something");
}
});
objProxy.name = "foo";
console.log(objProxy); // Proxy now has name attribute
console.log(obj); // And so does the original object

Get key from value in Json [duplicate]

This question already has answers here:
Javascript get Object property Name
(4 answers)
Closed 7 years ago.
I have a Json object in following format
MyJsonObject= {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
I want to get the key as return type if we pass value to function. Eg If I pass value =Man, function should return Human as return type. similarly, If I passed Tiger as value than I want to get Animal as return value.
Any help will be appreciated
Hi the snippet bellow should work.
You can try here http://jsfiddle.net/xtdqodzk/1/
MyJsonObject= {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
function find(value){
for(var prop in MyJsonObject ){
if(MyJsonObject.hasOwnProperty(prop)){
for(var i =0 ;i<MyJsonObject[prop].length;i++){
if(MyJsonObject[prop][i] === value){
return prop;
}
}
}
}
}
alert(find('Man'));
You can try to modify Object prototype
Object.prototype.findKey = function(value) {
for (var key in this) {
if (this.hasOwnProperty(key)) {
for (var i = 0; i < this[key].length; i++) {
if (this[key][i] === value) {
return key;
}
}
}
}
}
var MyJsonObject = {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
console.log(MyJsonObject.findKey('Man'));
The advantage of doing this way is if you have another json object you can call .findKey function on that object as well since all objects inherit functions and properties from Object.prototype object (prototypal inheritance).

Convert array to object properties JavaScript [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I have an object:
{
messages: {
foo: {
bar: "hello"
},
other: {
world: "abc"
}
}
}
I need a function:
var result = myFunction('messages.foo.bar'); // hello
How to create this function?
Thanks
I've written such a set of utility functions here:
https://github.com/forms-js/forms-js/blob/master/source/utils/flatten.ts
There's also the Flat library:
https://github.com/hughsk/flat
Either should suit your needs. Essentially it boils down to something like this:
function read(key, object) {
var keys = key.split(/[\.\[\]]/);
while (keys.length > 0) {
var key = keys.shift();
// Keys after array will be empty
if (!key) {
continue;
}
// Convert array indices from strings ('0') to integers (0)
if (key.match(/^[0-9]+$/)) {
key = parseInt(key);
}
// Short-circuit if the path being read doesn't exist
if (!object.hasOwnProperty(key)) {
return undefined;
}
object = object[key];
}
return object;
}

How can I create a new object from existing values? [duplicate]

This question already has answers here:
create object using variables for property name [duplicate]
(4 answers)
Closed 8 years ago.
I have
object.name = 'foo';
var value = 'bar';
...
var params = { object.name : 1, value : value};
I want a result equivalent to
var params = { foo : 1, value : bar };
what can I do?
Objects are sometimes called associative arrays, since each property is associated with a `string value that can be used to access it.
Try using [] to set object property -
object.name = 'foo';
var value = 'bar';
var params = { value:value};
params[ object.name] = 1;
Output:- {value: "bar", foo: 1}

deserialize JSON to JAVASCRIPT object [duplicate]

This question already has answers here:
Re-associating an object with its class after deserialization in Node.js
(4 answers)
Closed 6 years ago.
i have a question to deserialize JSON text to an javascript object, i test jquery and yui library, i have this class:
function Identifier(name, contextId) {
this.name = name;
this.contextId = contextId;
}
Identifier.prototype.setName = function(name) {
this.name = name;
}
Identifier.prototype.getName = function() {
return this.name;
}
Identifier.prototype.setContextId = function(contexId) {
this.contextId= contexId;
}
Identifier.prototype.getContextId = function() {
return this.contextId;
}
and i have this JSON:
{
"Identifier": {
"name":"uno",
"contextId":"dos"}
}
I want to the parse create an Identifier object, my problem is that this sentences:
var obj = jQuery.parseJSON('{"Identifier": { "name":"uno","contextId":"dos"}}');
or
var obj2 = JSON.parse('{"Identifier": { "name":"uno","contextId":"dos"}}');
Dont work, the var obj and obj2 aren't an Identifier object, how can i parse this?
Thanks
This question is not the duplicate, because it was made 5 years before than the question that Michael marks as duplicated
You could create a function that initializes those objects for you. Here's one I quickly drafted:
function parseJSONToObject(str) {
var json = JSON.parse(str);
var name = null;
for(var i in json) { //Get the first property to act as name
name = i;
break;
}
if (name == null)
return null;
var obj = new window[name]();
for(var i in json[name])
obj[i] = json[name][i];
return obj;
}
This creates an object of the type represented by the name of the first attribute, and assigns it's values according to the attributes of the object of the first attribute. You could use it like that:
var identifier = parseJSONToObject('{"Identifier": { "name":"uno","contextId":"dos"}}');
console.log(identifier);
Live example

Categories