Add new items in Object

I used this method to add new keys and values to my object.

Here is my code:

function orbitalPeriod(arr) {
  var GM = 398600.4418;
  var earthRadius = 6367.4447;
  var result = [];
  var s = {};
  for(let i=0; i<arr.length; i++){
    console.log(arr[i].name)
    // console.log(arr[i].name);
    // console.log(arr[i].avgAlt);
    s.name= arr[i].name
  }
  console.log(s)
  // console.log(result);
  // console.log(arr.length)
  // console.log(arr[0].name);
  // console.log(arr[0].avgAlt);
  // console.log(typeof(arr[0]));
  return arr;
}
orbitalPeriod([{name: "iss", avgAlt: 413.6}, 
{name: "hubble", avgAlt: 556.7}, 
{name: "moon", avgAlt: 378632.553}])

Output of s is -

{ name: 'moon' }

But I’m expecting,

{name:'iss',name:'hubble',name:'moon'}

qq
What’s going on here? :frowning:

s.name= arr[i].name

On each iteration, you overwriting the name property in s object.

It’s not possible to create an object like this:

{name:'iss',name:'hubble',name:'moon'}

Because as per MDN:

When using the same name for your properties, the second property will overwrite the first.

1 Like

maybe you want to get instead
[{name:'iss'},{name:'hubble'},{name:'moon'}]

this you can get

1 Like

Ya, I’m trying something like this :relaxed:
s

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.