20

Let's consider the following is my object:

var n = {"aa":"x","dd":'d'};

I am using square brackets in Object.assign. It gives the following result. [aa: "x", dd: "d"]. The final code is:

var n = {"aa":"x","dd":'d'};
var m = Object.assign([],n);

// result is 
[aa: "x", dd: "d"]

in the console.log __proto__ tells this is Array, if it is array following code giving the, unexpected token error

var v = ["sss":"ddd","ccc":"ddd"]; 

What does mean?

enter image description here

5
  • @MaheerAli I thought it was until I tried it May 17, 2019 at 17:13
  • 1
    arrays are just special objects they can have properties too. May 17, 2019 at 17:13
  • 1
    @MaheerAli it creates sort of an associative array with non-numeric keys
    – adiga
    May 17, 2019 at 17:13
  • This is just what Array.valueOf returns when you have extra keys set on an array.
    – Mark
    May 17, 2019 at 17:14
  • Use Object.assign({},n) instead. You are trying to clone map to array.
    – suketup
    May 17, 2019 at 17:15

5 Answers 5

19

Arrays are objects in JS

Arrays in JS are exotic objects, so you can assign properties to them just like any other object.

MDN says:

Arrays are list-like objects

...

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

Object.assign doesn't know the difference between an array and an object, and simply assigns keys from parameters 2+ to the object at parameter 1. This behavior shouldn't be too surprising.

const a = [];
a.foo = 42;
const b = Object.assign([], a);                  // sure, why not?
console.log(typeof a, typeof b, b.foo);          // => object object 42
console.log(Array.isArray(a), Array.isArray(b)); // => true true

The var a = ["foo": "bar"] syntax doesn't work because JS array initializers follow similar syntax to function calls. The array initializer is not syntactic sugar on the Array constructor, but it is similar in that it accepts a comma-delimited list of expressions. There's no reason to think it should behave in the same way as the object literal var obj = {"foo": "bar"} syntax, which has its own specification. That's a good thing, because it's poor practice to abuse arrays as key-value objects as much as it is to abuse functions as key-value objects:

const func = () => "hello";
func.foo = 42;
console.log(func.foo, typeof func, func()); // => 42 function hello

From the MDN article on array literals:

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

Expressions are "any valid unit of code that resolves to a value". The key: value syntax is not an expression itself, only part of the object initializer syntax, and it's absent in the MDN expression reference page.


Browser console printing is implementation-defined

Moving away from JS and into the browser, the image you've posted shows how Chrome logs arrays with properties, but this is implementation-defined according to the following specification found in console.log -> console.logger -> console.printer:

The printer operation is implementation-defined. It accepts a log level indicating severity, a List of arguments to print, and an optional object of implementation-specific formatting options. Elements appearing in args will be one of the following:

...

How the implementation prints args is up to the implementation, but implementations should separate the objects by a space or something similar, as that has become a developer expectation.

Furthermore, 2.3.3. Common object formats states:

Typically objects will be printed in a format that is suitable for their context. This section describes common ways in which objects are formatted to be most useful in their context. It should be noted that the formatting described in this section is applied to implementation-specific object representations that will eventually be passed into Printer, where the actual side effect of formatting will be seen.

An object with generic JavaScript object formatting is a potentially expandable representation of a generic JavaScript object. An object with optimally useful formatting is an implementation-specific, potentially-interactive representation of an object judged to be maximally useful and informative.

Empirical evidence supports the above statements:

Firefox 67.0

ff

Edge 42.17134.1.0

edge

Neither browser shows the array's properties between the brackets, only its numerically-indexed elements (if any exist). The fact that Chrome renders these properties in its implementation of the console spec does not obligate or imply that JS should allow this syntax in its array initializer. There's simply no relationship between the browser's console presentation and the language's syntax.

5

What you have here is an array that is abused as an object literal. An array has, for example, also a length property. Just like this, you can assign keys to an array, though you shouldn't do it.

It's not entirely clear what you want to to here, usually one uses Object.assign() with object literals rather than with arrays. They have their own functions.

Object.assign({}, n);

would be a sane use case.

5

Object.assign() just loops over the enumerable keys of all the objects from the 2nd parameter onwards and adds them to the target object.

So, Object.assign(arr, obj) roughly boils down to (polyfill):

for(key in obj)
  arr[key] = obj[key]

This technique can be used when you want to update a particular index of an array without mutating the original array (like in react)

So, this code

const arr = [1, 2, 3, 4]
const clone = [...arr]
clone[2] = 10;
console.log(arr, clone)

can be written like this:

const arr = [1, 2, 3, 4]
const clone = Object.assign([], arr, { [2]: 10 })
console.log(arr, clone)

2

If you want to change an object into array you should do this:

var n = {"aa":"x","dd":'d'};

for (let [key, value] of Object.entries(n)) {
console.log(`${key}: ${value}`);
}

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). The order of the array returned by Object.entries() does not depend on how an object is defined.

1

Arrays are {} in Javascript

Consider:

let obj = {"keyOne":"keyOneValue!", "keyTwo":'keyTwoValue!'};
let array = Object.assign([], obj);

console.log('Array is', array);
console.log('Array keys are currently: ', Object.keys(array));
console.log('array.keyOne value:', array.keyOne);
console.log('array.keyTwo value:', array.keyTwo);
console.log('But Array length is', array.length);
array.push('hello');
console.log('Array push one element array.push("hello")');
console.log('Array length after push', array.length);
console.log('Array keys are now!!!', Object.keys(array));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.