简体   繁体   中英

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.

If the condition will be fulfilled, simply push an object to your EMPLOYEES array:

let isAmerican = true;

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

if(isAmerican) {
    EMPLOYEES.push({
    id: 6,
    name: "Frank"
  })
}
console.log(EMPLOYEES)

Fiddle: https://jsfiddle.net/rqx35pLz/

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"}] : []
];

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"}] : []
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM