0

I'm looking to dynamically merge/insert objects to refactor a bunch of API request object types and I can't seem to find a clear answer.

let isThingTrue = true;

let dynamicObjectItem1 = {"foo": "bar"};

let dynamicObject = {
"item1": "stuff here",
"item2": "stuff here",
isThingTrue ? dynamicObject : <add nothing>
"item3": "stuff here
};

If isThingTrue is true, then object looks like:

{
"item1": "stuff here",
"item2": "stuff here",
"foo": "bar",
"item3": "stuff here
}

If isThingTrue is false, then object looks like:

{
"item1": "stuff here",
"item2": "stuff here",
"item3": "stuff here
}

Is this possible? Adding a value like this doesn't work.

let dynamicObjectItem1 = {"foo": "bar"};

let dynamicObjectStart = {
"item1": "stuff here",
"item2": "stuff here",
dynamicObjectItem1,
"item3": "stuff here"
};

Which produces:

{
"item1": "stuff here",
"item2": "stuff here",
"dynamicObjectItem1": {
   "foo": "bar"
   }
"item3": "stuff here"
};

Is there a clean way to make this work without a bunch of Object.assigns?

Derek Ball
  • 75
  • 1
  • 6
  • Just assign `undefined` to `foo` if you don't want the value `"bar"`, that should be as good as not having the property. – Bergi Jul 12 '23 at 20:44

1 Answers1

0

You can use spread syntax.

const makeObj = isThingTrue => {
  let dynamicObjectItem1 = {
    "foo": "bar"
  };
  return {
    "item1": "stuff here",
    "item2": "stuff here",
    ...isThingTrue && dynamicObjectItem1,
      "item3": "stuff here"
  };
}
console.log(makeObj(true));
console.log(makeObj(false));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80