A
A
Artem Prokhorov2021-06-16 19:26:51
JavaScript
Artem Prokhorov, 2021-06-16 19:26:51

How to add to an object a sub-object whose key name will be taken from a variable?

There is an object: let obj = []. In fact, I declare an array, but it console.logshows that it is an object.
So, push()it does not work for him, since it is an object. Adding a new element through obj.key = valuesolves the problem, but inserting keyyour value from the variable instead of it did not work, and I want something like this:

let obj = []
let href = window.location.href;
obj.href = value;


At the same time, href should be a URL, not the word "href".

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Neverov, 2021-06-16
@kotcich

What exactly is happening in your code and what do you plan to achieve with such a crutch?
In your case, you can do:
obj[href] = value
But making an array and calling it an object is wrong. As well as it is wrong to add properties to an array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question