create object key and property of object dynamically [duplicate] - javascript

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);

Related

How to create array of objects from array: javascript [duplicate]

This question already has answers here:
How to convert array of items to array of objects?
(2 answers)
Closed 1 year ago.
I am trying to convert an array of elements to an array of objects in Javascript (react)
Here is the data I am getting from my API
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210" ]
And I am trying to convert to an array of object which should look like this
options = [
{ value: "1.0.1.2", label: "1.0.1.2" },
{ value: "1.0.22.0", label: "1.0.22.0" },
{ value: "2.5.2.6", label: "2.5.2.6" },
];
I tried using the map function
versions = VersionloginData.data.versions.map((version) => [version.value, version.label])
But didn't work out well , i am getting undefined as value objects
You needed to return an object inside the map callback:
versions = VersionloginData.data.versions.map((version) => ({ value: version, label: version }))
Its should be.
const data = {
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210"]
}
const output = data.versions.map(item => ({ value: item, label: item }));
console.log(output);
Why your code is not working?
You are accessing incorrect nodes with [version.value, version.label]. value and label doesnot exist on version. Instead, you should return an object with keys value and label having same value.
you can try this
var options = []
versions.forEach((v)=>{
options.push({
value: v,
label: v,
})
})

Dynamically access object properties using a variable [duplicate]

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

Create id and check if it exists in an object array [duplicate]

This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
How generate a unique id and push it through an object to an array, on condition that this id property value does not already exist in any of the array objects?
As per React code excerpt below, function "saveColor" was supposed to do that, attaching current state background color, so that an object would look similarily to those in the palettes array:
state = {
backgroundColor: "red",
palettes: [
{id: 2, color: "crimson"},
{id: 1, color: "skyblue"},
{id: 0, color: "rebeccapurple"},
{id: 4, color: "magenta"}
]
}
saveColor = () => {
let previousPalettes = this.state.palettes;
previousPalettes.push(this.state.backgroundColor);
this.setState({
palettes: previousPalettes
})
}
It is not clear why you need id here, but if you really need it - look at this package https://www.npmjs.com/package/uuid

Iterating though object in array in React (ES6) [duplicate]

This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 5 years ago.
I have an object in array like the following:
bears: [
{
Yogi: "123kg",
Pooh: "110kg",
Grizly: "112kg",
BooBoo: "200kg",
Polar: "100kg",
}
]
`
What is the best way to iterate through such object in order to display both names and values in the row, like returning something in the type of: <p>${name} ${value}</p>
So I would display:
Yogi 123kg
Pooh 110kg
Grizly 112kg
BooBoo 200kg
Polar 100kh
It's an array containing an object, not an object. Anyway just get the first item of the array.
This should work:
Object.keys(bears[0]).map(key => <p>{`${key} ${bears[0][key]}`}</p>);
I think that the JSON object's structure itself is wrong.
It should be structured like this:
var bears = [{
name: "Yogi",
weight: "123kg"
}, {
name: "Pooh",
weight: "110kg"
}, {
name: "Grizly",
weight: "112kg"
}, {
name: "BooBoo",
weight: "200kg"
}]
Then you can go ahead and iterate through it using a for loop inside of the render() method like this.
render() {
var bearElements = [];
for (var bearIndex = 0; bearIndex < bears.length; bearIndex++) {
bearElements.push(
<p>{`${bears[bearElements].name}` `${bears[bearElements].weight}`}</p>
)
}
return (
<div>{bears}</div>
);
}

reuse key in the same object in javascript [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 7 years ago.
I am trying to avoid to repeat each time
$('.element1'),
$('.element1').html(),
in
myList = [
{
element: $('.element1'),
text: element.html(),
value: 'somevalue'
},
{
element: $('.element2'),
text: element.html(),
value: 'somevalue'
}
];
but actually it is not working, it shows me the eroor:
Uncaught ReferenceError: element is not defined
I need to define and keep everything only inside the "myList",
avoiding to define other external variables etc, and I would like to know how I can use something like this
I really appreciate any help
You want to separate your data from your logic a bit more, so that it can scale later
myList = [
{
element: '.element1',
value: 'somevalue'
},
{
element: '.element2',
value: 'somevalue'
}
];
myList.forEach(function(elem) {
$(elem.element).html(elem.value)
});
myList = [
{
element: $('.element1'),
value: 'somevalue'
},
{
element: $('.element2'),
value: 'somevalue'
}
];
for( var i in myList ) {
myList[ i ]["text"] = myList[ i ][ "element" ].html();
}
You have to declare the variable before.
Property/key of objects are not variable themselves in the current scope.
var element = $('.element1');
var element2 = $('.element2');
myList = [
{
element: element,
text: element.html(),
value: 'somevalue'
},
{
element: element2,
text: element2.html(),
value: 'somevalue'
}
];
Also check here for possible one time initialization of the object.
This would not save you so much typing and code.
Self-references in object literal declarations
is not really clear why you want to avoid to repeat them and keep all of them in the object, of course saving the processing of jquery functions is a reason.

Categories