how can i define a object with Variables? [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 years ago.
I want to add to Object with variables, like this
a = 'name'
object = {'age': 12, 'weight': 120}
I want this to
{'name': 'bob'}
I do this
object = {a: 'bob'}
but it give me
{'a': 'bob'}
how can I fixed it? I must use variables

Just assign it with the bracket notation after deleting the former content.
var a = 'name',
object = { 'age': 12, 'weight': 120 };
object = {}; // delete all properties
object[a]= 'Bob'; // assign new property
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');

You can't do this in one line. But you can do like this :
object = {};
object [a] = 'bob';

In ECMAScript 2015 there are computed property names:
var a = 'name';
var obj = {[a]:'fred'};
However there may not be sufficient support yet. See the MDN browser compatability table.

Related

Array.splice duplicate edit and insert after , unexpected result

In the following example (https://jsfiddle.net/dhkzwxr1/2/) :
I try to understand the behaviour of splice
const arr = [];
arr[0] = {name:"Jani",age:24};
arr[1] = {name:"Hege",age:32};
arr[2] = {name:"Stale",age:52};
arr[3] = {name:"Kai Jim",age:42};
arr[4] = {name:"Borge",age:25};
arr.splice(1, 0, {name:"Lene",age:27});
console.log(arr);
Insert at
Behave as expected
const arr2 = [];
arr2[0] = {name:"Jani",age:24};
arr2[1] = {name:"Hege",age:32};
arr2[2] = {name:"Stale",age:52};
arr2[3] = {name:"Kai Jim",age:42};
arr2[4] = {name:"Borge",age:25};
const jani = arr2[0];
jani.age = 19
arr2.splice(1, 0, jani);
console.log(arr2);
Output :
Array(6)
0: {name: "Jani", age: 19}
1: {name: "Jani", age: 19}
2: {name: "Hege", age: 32}
3: {name: "Stale", age: 52}
4: {name: "Kai Jim", age: 42}
5: {name: "Borge", age: 25}
length: 6
Why arr2[0].age === 19 and not 24 ?
This is not an issue with slice. What happens is that objects in JavaScript, like all other non-primitive values, are passed by reference.
So even if you insert an object into array, and update it after that, the variable will have the updated value. I think the most important thing to understand is that jani variable in your case does not have an actual value of the object, but just a reference to it.
like said commentator above Because you're inserting the same element into the array. The object referenced by jani is in the array twice once you splice it in.
and you should create a new object, you can do it by method Object.assign()
easy fix
var jani = Object.assign({}, arr2[0]);
working example
https://jsfiddle.net/fdtgvcLw/
When you assign one variable to another, it's not that both those variables are now linked by reference; you're misunderstanding what "pass by reference" means here.
A variable holding an object does not "directly" hold an object. What it holds is a reference to an object. When you assign that reference from one variable to another, you're making a copy of that reference. Now both variables hold a reference to an object. Modifying the object through that reference changes it for both variables holding a reference to that object.
When you assign a new value to one of the variables, you're just modifying the value that variable holds. The variable now ceases to hold a reference to the object, and instead holds something else. The other variable still holds its reference to the original object, the assignment didn't influence it at all.
Let's visualize:
var objOne = {
x: 1,
y: 2
};
// objOne -> { x: 1, y: 2 }
var objTwo = objOne;
// objOne -> { x: 1, y: 2 } <- objTwo
objTwo.x = 2;
// objOne -> { x: 2, y: 2 } <- objTwo (update object via objTwo variable)
objTwo = {};
// objOne -> { x: 2, y: 2 }, objTwo -> {}
This is how pass-by-reference works. Here objTwo is referring to objOne so whatever you do with objTwo will also happen with objOne.
It is not about splice. its with you have assigning object, and changing it's value to 19.
Then you insert another record to the array.
If you comment the var jani = arr2[0]; and splice it like you have done it before.
It would work.

How to set a property of a prototype object for a single class [duplicate]

This question already has answers here:
Crockford's Prototypal inheritance - Issues with nested objects
(3 answers)
Closed 4 years ago.
Say I change the object prototype like so:
Object.prototype.test = {val: 5, abc: 8};
Then I change a property of test for Array:
Array.prototype.test.abc = 20;
Then if I print the base test variable:
console.log(Object.prototype.test); // {val: 5, abc: 20}
console.log(({}).test); // {val: 5, abc: 20}
console.log(([]).test); // {val: 5, abc: 20}
How do I still have arrays inherit val as 5, but have an abc value of 20 without affecting Object's prototype
In your example Array.protoype does not have its own test property. So when you try to access it with Array.prototype.test.abc = 20; it looks up the prototype chain and find the .test object on Object.prototype and sets its .abc value to 20.
You can give Array.prototype it's own property test with something like:
Object.prototype.test = {val: 5, abc: 8};
Array.prototype.test = Object.assign({}, Object.prototype.test)
Array.prototype.test.abc = 20;
console.log(({}).test.abc); // 8
console.log(([]).test.abc); // 20
You could also link the test object from Array to Object so properties not found on Array.prototype.test will defer up the chain to Object.prototype.test, although this starts to get confusing:
Object.prototype.test = {val: 5, abc: 8};
Array.prototype.test = Object.create(Object.prototype.test)
Array.prototype.test.abc = 20;
console.log(([]).test.abc); // shadows with it's own abc
Object.prototype.test.abc = 500 // changes in object have no effect
console.log(([]).test.abc); // still 20
console.log(([]).test.val); // no val on Array's test so it defers to object prototype
Object.prototype.test.val = 100 // changing object changes array
console.log(([]).test.val);
…not that I really recommend any of this beyond test and exploring the ecosystem.

Look up object keys by value [duplicate]

This question already has answers here:
Swap key with value in object
(25 answers)
Closed 5 years ago.
Object = {"o":"s","e":"w"}
If I have this object, is there a way to perform reverse lookups on it?
Something like:
Object.invert()["s"]
> "o"
You want to revert the key/value mapping.
var test = {a: "b", c: "d"}
var reverted = {}
for(var key in test) {
reverted[test[key]] = key
}

destructure object in javascript es6 when keys are integers [duplicate]

This question already has answers here:
Object destructuring with property names that are not valid variable names
(2 answers)
Closed 6 years ago.
When we have an object in JS like
var obj = {a: "apple", p: "pen"};
then we can destructure it as follows
var {a, p} = obj; /* a = 'apple', p = 'pen' */
i want to know in case when keys are integers, how can we destructure it ? since we cannot declare integers as variable name
var obj = {0: 'pineapple', 1: 'pen'};
Just like any other assigning to new variable names
var {0:a, 1:b} = obj;

Access array inside an object

var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
I want to access array in object b. ie, maths, physics, chemistry .
This may be a simple question but i am learning....Thanks
Given the arrays in the object b (note that you have a syntax error in the code you provided)
var b = {
maths: [12, 23, 45],
physics: [12, 23, 45],
chemistry: [12, 23, 45]
};
maths, physics, and chemistry are called properties of the object stored in variable b
You can access property of an object using the dot notation:
b.maths[0]; //get first item array stored in property maths of object b
Another way to access a property of an object is:
b['maths'][0]; //get first item array stored in property maths of object b
var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
console.log(b.maths);
// or
console.log(b["maths"]);
// and
console.log(b.maths[0]); // first array item
var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
// using loops you can do like
for(var i=0;i<b.maths.length;i++){
console.log(b.maths[i]);//will give all the elements
}
there are simple:
b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
b.maths[1] // second element of maths
b.physics
b.chemistry
You need to set the variable b like this :
var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
Then you can access your arrays inside b by using b.maths, b.physics and b.chemistry.

Categories