-1

OK, the title may be confusing, but here is what I am trying to do: I have two objects

var smallObject = {
"FirstName" : "pacman",
"LastName" : "gamer",
"SSN" : "123-45-6789"
}

var largeObject = {
"FirstName" : "pacman",
"LastName" : "gamer",
"SSN" : "123-45-6789",
...
...
...
...
}

I want to be able to only copy (replace if different) the values in smallObject but not add any of the additional from largeObject

Pacman
  • 2,183
  • 6
  • 39
  • 70
  • What have you tried? Do you get any errors? – XCS Dec 14 '17 at 22:14
  • havent tried anything, I dont know how to do it other than Object.Assign which will copy also the items in largeObejct which I dont need – Pacman Dec 14 '17 at 22:28

3 Answers3

0

Just use a simple loop:

for (const p in smaller)
    smaller[p] = larger[p];

If you were looking for any new ES6 builtin similar to Object.assign: no, there isn't any.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • this will assign `undefined` to every property of `smaller` that doesn't exists in `larger`. – Olian04 Dec 14 '17 at 23:06
  • @Olian04 The `larger` object in the question has all the properties that `smaller` has. I thought it was implied by the naming that `larger` has the same properties as the other, and more? Even if not, it's trivial to fix by adding a `if (p in larger)` condition. – Bergi Dec 14 '17 at 23:26
0

One of the easy ways to do this is as @Bergi said. Create a for-in loop and go through the properties of the smallObject and assign the value of the corresponding largeObject property to the smallObject.

var smallObject = {
  "FirstName": "pacman",
  "LastName": "gamer",
  "SSN": "123-45-6789"
}

var largeObject = {
  "FirstName": "Pacman",
  "LastName": "Bright",
  "SSN": "123-45-1337",
  "av": "abca",
  "az": "doda",
  "asdW": "dawd"
}


for(var prop in smallObject) {
  if(smallObject.hasOwnProperty(prop) && largeObject.hasOwnProperty(prop)) {
    smallObject[prop] = largeObject[prop]
  }
}

console.log(smallObject)
Siggy
  • 324
  • 2
  • 11
  • [Don't use `object.hasOwnProperty(prop)`](https://stackoverflow.com/a/45014721/1048572). – Bergi Dec 14 '17 at 22:52
  • It's correct that you don't have to do any `Object.hasOwnProperty` calls if you know that the `Object` you're working with is an plain object. But you will have to check if the property exists in `largeObject`. – Siggy Dec 14 '17 at 22:57
  • Then do that by a simple `prop in largeObject` :-) – Bergi Dec 14 '17 at 23:24
0

Assuming that the smallObject isn't necessary a strict subset of largeObject.

const smallObject = {"a":"A","b":"B","c":"C","q":"Q"};
const largeObject = {"a":"AA","b":"BB","c":"CC","d":"DD","e":"EE","f":"FF"};

const resultObj = Object.entries(smallObject).reduce((res, [k, v]) =>
  ({...res, [k]: (largeObject[k] === undefined) ? v : largeObject[k]}), {});

console.log(resultObj);
Olian04
  • 6,480
  • 2
  • 27
  • 54