This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 years ago.
I have a large object with multiple objects nested within it. I have a function that will take the key of one of the objects, and I want to add a new property to the sub-object that is called. Something like https://jsfiddle.net/cf15xdfm/2/
var my_object = {
object1: {
key: 'value',
key2: 'value2'
},
object2: {
key: 'othervalue',
key2: 'another'
}
}
function doSomething(obj_key) {
// add a new property to the object
my_object.obj_key.new_prop = 'this_new_prop';
}
doSomething('object1');
console.dir(my_object);
How do I reference the variable obj_key in the doSomething method so that I can alter the desired object?
Make use of brackets notation for accessing dynamic keys
var my_object = {
object1: {
key: 'value',
key2: 'value2'
},
object2: {
key: 'othervalue',
key2: 'another'
}
}
function doSomething(obj_key) {
// add a new property to the object
my_object[obj_key].new_prop = 'this_new_prop'; // using bracket notation here
}
doSomething('object1');
console.dir(my_object);
You can use:
my_object[obj_key].new_prop='this_new_prop';
You can call properties as string like this:
obj['property_name']
So you should do this:
my_object[obj_key].new_prop = 'this_new_prop';
Edit: Sorry didn't see the answer was already there
Related
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 6 months ago.
I am trying to read values from JSON Object using a function that is dynamic.
Sample JSON Object -
var test =
{
"test1": {
"test2": "value2"
},
"test3": {
"test4": {
"test5": "value5"
}
}
}
Now I need to read the test5 value and test2 value so I created the below method and called it twice by passing the argument.
readValue('test1.test2');
readValue('test3.test4.test5');
function readValue(val){
console.log(eval(`test.${val}`));
}
This code is working fine, I am able to get the output.
But is there any alternative to use eval here ??
Better than eval, split your compound key by a dot and iterate it:
let val = (obj, keys) => keys.split('.').reduce(Reflect.get, obj)
var test =
{
"test1": {
"test2": "value2"
},
"test3": {
"test4": {
"test5": "value5"
}
}
}
console.log(val(test, 'test1.test2'))
console.log(val(test, 'test3.test4.test5'))
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I was calling a function and pass array of objects as first argument and second argument was object property of first argument but I don't know why map func doesn't accepting second argument property
Here code plz see it once
const myfunc = (arrObj, property) => {
const arr1 = arrObj.map(item => {
return item.property
}
return arr1:
}
const arrObj = [{
title: 'book',
body: 'hello'
},
{
title: 'cup',
body: 'hii'
}
];
// Func call
console.log(myfunc(arrObj, 'title'));
Use lowercase for const, return, console.
Return a value (an array, in this case) from your function that you can log.
Use item[property] to access the title property. There is no "property" key in those objects.
Make sure you close all of your parentheses.
function myfunc(arrObj, property) {
return arrObj.map(item => item[property]);
}
const arrObj=[{title:"book",body:"hello"},{title:"cup",body:"hii"}];
console.log(myfunc(arrObj, 'title'));
There are multiple errors in your code. First keywords like return,const,console are all case sensative. Secondly you are not returning from the function. Third since property is a variable you have to use square braces instead of dot
const myfunc = (arrObj, property) => {
return arrObj.map(item => {
return item[property]
})
}
const arrObj = [{
title: 'book',
body: 'hello'
},
{
title: 'cup',
body: 'hii'
}
];
// Func call
console.log(myfunc(arrObj, 'title'));
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 2 years ago.
I feel like my problem is really easy to solve, but I cannot see it. I have simple thing to do, get myObject from another function and store this in my storage object. For this task I created storageHandler function. Everything works fine, but Object.assign is not reaching my 'ID' that I declared in this function earlier. This is weird because I don't know how to tell my function that 'ID' is variable, not a string. I just expect it to be {1212313: {...}} but instead it gives me {ID: {...}}.
Someone have any idea how to fix it?
let storage = {}
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com'
}
storageHandler = data => {
const {ID} = data;
Object.assign(storage, {ID: data})
console.log(storage)
}
storageHandler(myObject)
That's because in javascript this
a = { b: 1 };
is the same as
a = { "b": 1 };
You should change the Object.assign() for something like this
storage[ID] = data;
You should use the value of ID as key of object using [].
Object.assign(storage, {[ID]: data})
You are using string as a property name. Use computed property name like [ID] instead of ID. Computed property allows you to have an expression be computed as a property name on an object.
let storage = {};
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com',
};
storageHandler = (data) => {
const { ID } = data;
Object.assign(storage, { [ID]: data });
console.log(storage);
};
storageHandler(myObject);
This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 3 years ago.
I'm looking to do something like the task here Self-references in object literals / initializers , except that it would be for the value of an aunt/uncle key, or the sibling key of the parent object. For example:
const obj = {
parent: {
child: {
aunt: /* aunt object */
}
},
aunt: {
foo: {
bar: 1
}
}
}
There's a very similar ask here Reference nested 'sibling'-property in object literal but unfortunately, not quite what I'm looking for. Ideally, the solution would be extensible and probably would need to be to handle cases where I'd want to access a great-grandcousin object related to a key if need be. Thanks!
It's not possible in a single object literal. You'd have to define the object first, then assign to the aunt key .
const obj = {
parent: {
child: {
}
},
aunt: {
foo: {
bar: 1
}
}
};
obj.parent.child.aunt = obj.aunt;
console.log(obj.parent.child.aunt === obj.aunt)
Or, you can define aunt beforehand:
const aunt = {
foo: {
bar: 1
}
};
const obj = {
parent: {
child: {
aunt
}
},
aunt
};
console.log(obj.parent.child.aunt === obj.aunt)
This question already has answers here:
How to set a Javascript object values dynamically?
(7 answers)
Closed 4 years ago.
I want to create a new object dynamically and insert into the inside of columns object
dynamicCreate = [
{
columns: {
title: {
title: "Title"
}
}
}
]
Create dynamically like
name: {
title: "Name"
},
and insert next of
title: {
title: "Title"
},
You can try using the dot notation
var obj={};
obj.title={};
obj.title.title="name";
console.log(obj)
Javascript is a dynamic language. so you can assign any props dynamically to the object.
var obj={
name:'foo'
};
obj.extraInfo={
bar:'baz'
}
console.log(obj);