Object Assign cloning undefinied properties

Asked

Viewed 46 times

0

I need to clone my Objects array so that the Undefined properties do not overwrite an existing property.

const myArray = [

    {
        "tecnico": "INS-MAN-RENAN M/RENAN C",
        "horas": "08:30:00",
        "2021-04-18": "21.94502"
    },
    {
        "tecnico": "INS-MAN-RENAN M/RENAN C",
        "horas": "08:30:00",
        "2021-04-18": ""
    },
    {
        "tecnico": "INS-MAN-RENAN M/RENAN C",
        "horas": "08:30:00",
        "2021-04-23": ""
    },
  
]

console.log(Object.assign({}, ...myArray));

I need to get the following result:

{
  "tecnico": "INS-MAN-RENAN M/RENAN C",
  "horas": "08:30:00",
  "2021-04-18": "21.94502",
  "2021-04-23": ""
}

  • It is not cloning what you seek. Wouldn’t it be reducing to an element? If it will even reduce what the criteria for choosing the data in the case of keys already populated with different values. Example: If there are two objects in the array whose key hour are like this {"horas": "08:30:00"}, {"horas": "12:00:00"} ?

  • It would clone because the repeated keys will be reduced to an object as in the above case and the ones that are not will be inserted in the same object ... the problem is when you find an equal key with an undefined value and end up overwriting the previous value, as in the case of the date 2021-04-18

  • 1

    I repeat is not cloning is reducing, see the example https://ideone.com/eSk8Rm

1 answer

1


The idea of using ...myArray in the Object.assign is good but as you noticed vis always overwrite old values with new ones, and end up overwriting the value you want for an empty string.

You have to create a reducer check if there is already a defined value and if the new value you will define is an empty string or not. You can do it like this:

const myArray = [{
    "tecnico": "INS-MAN-RENAN M/RENAN C",
    "horas": "08:30:00",
    "2021-04-18": "21.94502"
  },
  {
    "tecnico": "INS-MAN-RENAN M/RENAN C",
    "horas": "08:30:00",
    "2021-04-18": ""
  },
  {
    "tecnico": "INS-MAN-RENAN M/RENAN C",
    "horas": "08:30:00",
    "2021-04-23": ""
  },
]

const merge = (arr) => arr.reduce((obj, entry) => {
  for (const key in entry) {
    if (typeof obj[key] !== 'undefined' && entry[key] === '') continue
    obj[key] = entry[key]
  }
  return obj

}, {})

console.log(merge(myArray))

  • Thank you Sergio, really using reduce and checking the Keys with Undefined values solved my problem. I imagined that through Object Assign, Keys with Undefined values were ignored.

  • Good! If you want you can mark the answer as accepted

Browser other questions tagged

You are not signed in. Login or sign up in order to post.