anon
anon

Reputation:

How to update certain property of an object from another object?

I have an object as follows:

const params1 = {
  FunctionName: "Foo",
  Environment: {
    Variables: {
      test: "test"
    }
  }
}

And I have another object as follows:

const params2 = {
  FunctionName: "Bar",
  Something: "Something",
  SomethingMore: "SomethingMore",
  Environment: {
    Variables: {
      sample1: "sample1",
      sample2: "sample2"
    }
  }
}

I just want to append all the environment variables from params2 to param1, so params1 should finally be something like this:

{
  FunctionName: "Foo",
  Environment: {
    Variables: {
      test: "test",
      sample1: "sample1",
      sample2: "sample2"
    }
  }
}

How can I achieve the same, I am able to do this using the following code,

params.Environment.Variables = {
  ...params.Environment.Variables,
  ...oldVars.Environment.Variables
}

But I have a restriction that I cannot use the spread operator, please help!

Upvotes: 0

Views: 36

Answers (3)

Sandeep Kaushik
Sandeep Kaushik

Reputation: 11

const params1 = {
      FunctionName: "Foo",
      Environment: {
        Variables: {
          test: "test"
        }
      }
    }
    const params2 = {
      FunctionName: "Bar",
      Something: "Something",
      SomethingMore: "SomethingMore",
      Environment: {
        Variables: {
          sample1: "sample1",
          sample2: "sample2"
        }
      }
    }
    let param3={...params2}
    for(let el in params1.Environment.Variables){
      param3['Environment']['Variables'][el]=el;

    }
    console.log('hidhjjd=',param3)

Upvotes: 0

Chamal Perera
Chamal Perera

Reputation: 313

You can use a for in loop.

const params1 = {
  FunctionName: "Foo",
  Environment: {
    Variables: {
      test: "test"
    }
  }
}

const params2 = {
  FunctionName: "Bar",
  Something: "Something",
  SomethingMore: "SomethingMore",
  Environment: {
    Variables: {
      sample1: "sample1",
      sample2: "sample2"
    }
  }
}

for (const key in params2.Environment.Variables) {
  params1.Environment.Variables[key]=params2.Environment.Variables[key];
}

console.log(params1)

Upvotes: 1

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

You can do this using object.assign

const params1 = {
  FunctionName: "Foo",
  Environment: {
    Variables: {
      test: "test"
    }
  }
}

const params2 = {
  FunctionName: "Bar",
  Something: "Something",
  SomethingMore: "SomethingMore",
  Environment: {
    Variables: {
      sample1: "sample1",
      sample2: "sample2"
    }
  }
}

Object.assign(params1.Environment.Variables,params2.Environment.Variables)

console.log(params1)

Upvotes: 2

Related Questions