0

I wanna merge 2 objects.

One object is the default form.

let data = {
  weight: '',
  DOB: '',
  gender: '',
}

The other is irregular like below that

let temp1 = {
   weight: '19.2',
}

let temp2 = {
   DOB: '1992-11',
}

let temp3 = {
   DOB: '1992-11',
   gender: 'Male',
}

let temp4 = undefined;

If I merge data and temp1, the result should be

let data = {
  weight: '19.2',
  DOB: '',
  gender: ''
}

If I merge data and temp3, the result should be

let data = {
  weight: '',
  DOB: '1992-11',
  gender: 'Male',
}

If I merge data and temp4, the result should be

let data = {
  weight: '',
  DOB: '',
  gender: ''
}

Give me some advice to achieve it.

Thanks in advance.

4

2 回答 2

5

You can use Object.assign():

let data = {
  weight: '',
  DOB: '',
  gender: '',
}


let temp3 = {
   DOB: '1992-11',
   gender: 'Male',
}

data = Object.assign(data, temp3);

or if you don't want the data object to change:

let data2 = Object.assign({}, data, temp3);

The spread operator can also be used, which basically is the same, just that the original data object doesn't change:

data = { ...data, ...temp3 };
于 2018-12-27T11:54:40.260 回答
1

with jQuery you can use $.extend()

let data = {
  weight: '',
  DOB: '',
  gender: '',
}
let temp1 = {
   weight: '19.2',
}

console.log($.extend(data,temp1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

OR use javascript spread operator ... as following

let data = {
  weight: '',
  DOB: '',
  gender: '',
}

let temp3 = {
   DOB: '1992-11',
   gender: 'Male',
}

data={...data,...temp3}
console.log(data)

If the keys are same then the value from righmost object is used

于 2018-12-27T12:02:22.097 回答