For example, can I do this?:
{
a: b: c: d: 1,
e: 2,
geh: function() { alert("Hi!") }
}
EDIT: Is there some way I can avoid doing this?:
{
a: 1,
b: 1,
c: 1,
d: 1,
e: 2,
geh: function() { alert("Hi!") }
}
You cannot. Property keys are unique. Follow TravisJ 's advice. You might want to look up the term 'multimap', too.
Objects are same as variables in JavaScript, the only difference is that an object holds multiple values in terms of properties and methods. In JavaScript, an object can be created in two ways: 1) using Object Literal/Initializer Syntax 2) using the Object() Constructor function with the new keyword.
assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target. It returns the target object which has properties and values copied from the target object.
In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function.
An update to this (in terms of the latest JavaScript abilities) avoiding unwanted defined vars:
{ let v; var obj = { "a": (v = 'some value'), "b": v, "c": v }; }
This will mean v
won't be defined outside the block, but obj
will be.
Another way of doing the same thing is:
var v; var obj = { "a": (v = 'some value'), "b": v, "c": v };
You could set a line of equality between various properties:
var foo = {};
foo.a = foo.b = foo.c = "Hello";
Or you could just create a method that does the mass-assignment for you:
var foo = {
setValue: function( props, value ) {
while ( props.length ) this[ props.pop() ] = value;
}
}
foo.setValue( [ "a", "b", "c" ] , "Foo" );
You could try this. It's not the syntactic sugar you're looking for (eg. {a,b,c:1, d:2}
) but it's another way to do it, although all of these answers are pretty much fine.
(object,fields,value)=>Object.assign(object||{}, ...fields.map(f=>({[f]:value}) ))
Explanation:
(object,fields,value)=>
Takes an object (or falsey value if you want a new object, feel free to rearrange the argument order)
Object.assign(object||{},
Will return an object based on object
and it will mutate the object. To disable this, simply add a first argument object literal like this Object.assign({}, object || {}, ...
...fields.map(f=>({[f]:value}) )
Will spread the array of fields mapped to objects as a list of extra arguments to Object.assign
. ['a','b'].map(f=>({[f]:value}) )
will give [{a:value}, {b:value}]
and f(...[{a:1},{b:1}])
is like f({a:1},{b:1})
. Object.assign
does the rest :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With