繁体   English   中英

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

[英]Javascript - Add Array of Objects to existing Array of Objects

我有一个Apple客户,我有一个Api Controller ,该Object CustomerObject Customer作为参数,并使用这些新Apple更新数据库中现有的一个:

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

我想使用Javascript将这些新的Apple添加到“客户”中的当前Apple 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)以上命令甚至没有运行Array.prototype.push.apply(updatedCustomer.apples, this.selectedApples)但是它也没有给我错误。 没事。 如果我返回将客户和苹果分开发送到我的控制器,则可以使用,但我不想这样做。

使用spread语法。

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

扩展语法允许将迭代式(例如数组表达式或字符串)扩展到期望零个或多个参数(对于函数调用)或元素(对于数组文字)的扩展,或将对象表达式扩展在零个或多个键值对(用于对象文字)是必需的。

如何使用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/

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

暂无
暂无

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

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