0

Using JavaScript, how can I set property of an object that already has property with the same name? For example, what i want to output is:

var obj = {
    name: "foo"
};

obj[name] = "baz";

Normal output is:

console.log(obj) => {name:baz}.

I want to output:

console.log(obj) => {name:foo,name:baz}.

I know that is not the best practice, but is that possible?

ahwayakchih
  • 2,101
  • 19
  • 24
Mert
  • 474
  • 2
  • 8
  • 21
  • 5
    it is impossible to have two keys that are the same in an object. Maybe you should think about using an array if you need multiple values. – epascarello Oct 18 '19 at 14:37
  • 1
    I'm not sure what your reasoning is, but ask yourself: _"what would `obj.name` point to if you could have multiple of the same keys?"_ If you want to store multiple names, either use `const names = [...]` or `obj = { names: [] }` – Yannick K Oct 18 '19 at 14:44
  • thanks for response. I try to dynamic create obj by months. its 13 piece. One mouth must be dublicate in object. why i am using this method. any advice for that ? – Mert Oct 18 '19 at 14:48

2 Answers2

0

You can read about core js concepts and also about basic data types in programming, like Maps and Arrays.

I can try to guess that your task is to store some similar data structures in array:

var list = [{name:'foo'},{name:'baz'}]
layonez
  • 1,746
  • 1
  • 16
  • 20
0

You simply can't do that. The latest value of the property will always override the previous one.

Even merging objects with same property names won't help you - shallow merge, or deep merge.

However, there are a few very weird cases with some JavaScript frameworks where this might happen - in Vue.js, for instance. But that misses the point since we're considering only plain Javascript.

d0st
  • 127
  • 1
  • 7