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?

1
  • Just assign undefined to foo if you don't want the value "bar", that should be as good as not having the property. Commented Jul 12, 2023 at 20:44

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.