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

时间:2018-10-11 06:25:08

标签: javascript arrays ecmascript-6

我有一些类似于下面的对象的静态数组常量。

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

现在,我仅需要基于某些条件为真时添加最后一个元素。例如isAmerican()为真。

有人可以帮助我根据条件添加元素吗?谢谢。

3 个答案:

答案 0 :(得分:1)

如果条件将得到满足,只需将一个对象推入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)

提琴:https://jsfiddle.net/rqx35pLz/

答案 1 :(得分:1)

您可以使用传播运算符来实现:

export const EMPLOYEES = [
    {
        id: 2,
        name: "John",
    },
    {
        id: 3,
        name: "Doe",
    },
    {
        id: 4,
        name: "Bull",
    },
    {
        id: 5,
        name: "Scott",
    },
    ... isAmerican() ? [{ id: 6, name: "Jemmy"}] : []
];

答案 2 :(得分:0)

您应该从不修改(或尝试修改)常量。我可以看到两种方法:

  1. 创建一个纯函数以返回一个新常量,并将新对象添加到数组中
  2. 在常数的定义中使用扩展运算符

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

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