Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add object element in array based on condition

I have static array constant of objects something similar to below.

export const EMPLOYEES = [
  {
    id: 2,
    name: ‘John’,
  },
  {
    id: 3,
    name: ‘Doe’,
  },
  {
    id: 4,
    name: ‘Bull’,
  },
  {
    id: 5,
    name: ‘Scott’,
  },
];

Now I need to add the last element only based on if some condition is true. Some this like if isAmerican() is true.

Can somebody help me here how to add element based on the condition? Thanks.

like image 652
brig Avatar asked Mar 20 '26 10:03

brig


2 Answers

You can do it using spread operator:

export const EMPLOYEES = [
    {
        id: 2,
        name: "John",
    },
    {
        id: 3,
        name: "Doe",
    },
    {
        id: 4,
        name: "Bull",
    },
    {
        id: 5,
        name: "Scott",
    },
    ... isAmerican() ? [{ id: 6, name: "Jemmy"}] : []
];
like image 183
wang Avatar answered Mar 23 '26 01:03

wang


You should never modify (or try to modify) a constant. I can see two ways you can do this:

  1. Create a pure function to return a new constant with the new object added to the array
  2. Use a spread operator in the definition of the constant

Option 1: Pure function

function makeNewArray(array, objectToAppend, isAmerican) {
    return isAmerican ? [...array, objectToAppend] : array
}

const EMPLOYEES = [
    {
        id: 2,
        name: "John",
    },
    {
        id: 3,
        name: "Doe",
    },
    {
        id: 4,
        name: "Bull",
    },
    {
        id: 5,
        name: "Scott",
    }
];

const arrayWithAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "American Frank"}, true);
const arrayWithoutAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "Not American Frank"}, false);

console.log(arrayWithAmerican);
console.log(arrayWithoutAmerican);

Option 2: Spread operator

function isAmerican(){
    // generic code here.
    return true;
}

const EMPLOYEES = [
    {
        id: 2,
        name: "John",
    },
    {
        id: 3,
        name: "Doe",
    },
    {
        id: 4,
        name: "Bull",
    },
    {
        id: 5,
        name: "Scott",
    },
    ... isAmerican() ? [{ id: 6, name: "American Frank"}] : []
];
like image 27
Mr.Turtle Avatar answered Mar 22 '26 23:03

Mr.Turtle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!