Javascript - 将对象数组添加到现有的对象数组中

时间:2017-10-31 10:51:41

标签: javascript

我有一个带苹果的客户,我有Api ControllerObject Customer作为参数,并使用这些新苹果更新数据库中现有的一个:

[HttpPut("Update")]
    public async void Put([FromBody]Customer customer)
    {
        await _repository.UpdateCustomer(customer);
    }

使用Javascript,我想将这些新苹果添加到客户当前的List苹果中。阅读SO应该看起来像:

addApplesToCustomer_method: function () {
        var updatedCustomer = this.currentCustomer;
        Array.prototype.push.apply(updatedCustomer.apples, this.selectedApples);

        $.ajax({
            url: 'api/customer/update',
            type: 'PUT',
            contentType: "application/json",
            data: JSON.stringify({
                customer: updatedCustomer
            }),
            success: function () {
                alert('success');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('Error: ' + textStatus + '\n' + errorThrown);
            }
        });
    }

currentCustomer是我们要更新的客户。 selectedApples是我们要添加到现有List个苹果客户的新Array个苹果。

然而,由于我添加了Array.prototype.push.apply(updatedCustomer.apples, this.selectedApples),但上面甚至没有运行,但它也没有给我一个错误。什么都没发生。如果我回去将客户和苹果单独发送到我的控制器,它可以工作,但我不想这样做。

2 个答案:

答案 0 :(得分:2)

使用spread语法。

updatedCustomer.apples.push(...this.selectedApples);
  

Spread语法允许迭代,例如数组表达式或字符串   在零或多个参数的地方扩展(用于函数   调用)或元素(对于数组文字)是期望的,或对象   要在零个或多个键值对的位置展开的表达式   (对象文字)是预期的。

答案 1 :(得分:0)

Array.push(object)

将对象推到数组上怎么样?
let objectArray = []

let apple = {
  name: 'Apple',
  size: 'medium'
}

let orange = {
  name: 'Orange',
  size: 'large'
}

// Create an initial list with apples
for (var i = 0; i < 10; i++) {
  objectArray.push(apple)
}

// Now add an orange to that list
objectArray.push(orange)

// The resulting array contains 10 apples, 1 orange.
console.log(objectArray)

这里是JSFiddle:http://jsfiddle.net/j7kcjjqh/

(检查控制台以查看结果)

相关问题