reuse key in the same object in javascript [duplicate] - javascript

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.

Related

Having issue with getting value from object variable. No errors showing

I created an array called animals containing two objects. I want to get a value from the name variable in the object animals and insert that value in a return statement in the map method. I used ${} to access the variable.
const Animals = [{
name: "Lion",
type: "Carnivore",
},
{
name: "Cow",
type: "Herbivore",
},
];
window.addEventListener("DOMContentLoaded", function() {
let display = Animals.map(function(item) {
return '<h1>${item.name}</h1>';
});
console.log(display);
});
Now I'm supposed to get in the console an array of two items containing the values of the variables -- the result should look like this ['<h1>Lion</h1>', '<h1>Cow</h1>']. But instead I get this ['<h1>${item.name}</h1>', '<h1>${item.name}</h1>']. As you can clearly see, for some reason the ${} was unable to access the variable and get the value. I don't know why this's happening. Console log shows no errors. Plz help me resolve this issue. Thanks in advance.
Check in your code instead of:
'<h1>${item.name}</h1>'
Should be:
`<h1>${item.name}</h1>`
Here is the documentation for Template literals (Template strings)
Demo:
const Animals = [{
name: "Lion",
type: "Carnivore",
},
{
name: "Cow",
type: "Herbivore",
},
]
const display = Animals.map(({ name }) => `<h1>${name}</h1>`)
console.log(display)
Variables inside ${...} structures are template/string literals syntax but in order for them to work they need to be enclosed with backticks instead of single/double quotes.
const animals=[{name:"Lion",type:"Carnivore"},{name:"Cow",type:"Herbivore"}];
window.addEventListener("DOMContentLoaded", function() {
const display = animals.map(function(item) {
return `<h1>${item.name}</h1>`;
});
console.log(display);
});
const Animals = [{
name: "Lion",
type: "Carnivore",
},
{
name: "Cow",
type: "Herbivore",
},
];
window.addEventListener("DOMContentLoaded", function() {
let display = Animals.map(function(item) {
return '<h1>'+item.name+'</h1>';
// return `<h1>${item.name}</h1>`;
});
console.log(display);
});

create object key and property of object dynamically [duplicate]

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

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

how to get access from an attribute to other objects atributtes [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 5 years ago.
Im totally new in JS. Could someone help me please? I need to prepare some objects atributes which depends on other objects attributes
How can I achive that?
I tried that solution:
var Photo = {
current: {
coordinates: "2208,1922",
name: "current"
},
start: {
coordinates: '2408,1822',
name: 'start',
newCoordinates: Photo.current.coordinates
}
};
I'm getting an error:
module initialization error: TypeError
var current = {
coordinates: "2208,1922",
name: "current"
}
var Photo = {
current: current,
start: {
coordinates: '2408,1822',
name: 'start',
newCoordinates: current.coordinates
}
};
console.log(Photo);
You just need to wait for the object to be initialized, then you can grab that property. See this code:
var Photo = {
current: {
coordinates: "2208,1922",
name: "current"
},
start: {
coordinates: '2408,1822',
name: 'start'
}
};
Photo.start.newCoordinates = Photo.current.coordinates; // 2208,1922

Retrieve Index When Passing Object to Function

I'm passing an Object from an array of objects to a function. Is it possible to still retrieve the index number somehow from the object in the function?
I'm doing this in javaScript specifically within the controller of AngularJS.
For instance
var array= [
{
name: "name1"
},
{
name: "name2"
}
];
function( passedInObjectFromArray ) {
return passedInObjectFromArray.indexVal;
}
Yes you can do,
$scope.retrieveIndex = function(passedInObjectFromArray){
return array.indexOf(passedInObjectFromArray);
}

Categories