简体   繁体   English

如何根据条件在数组中添加对象元素

[英]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. 如果isAmerican()为true,则isAmerican()这种情况。

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: 如果条件将得到满足,只需将一个对象推入您的EMPLOYEES数组即可:

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/ 小提琴: 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 选项1:纯功能

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 选项2:点差运算符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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