简体   繁体   English

我怎样才能正确地传播这些阵列?

[英]how can I spread these arrays properly?

I need to insert an empty item as the first item in an array of data which will be databound to a dropdown.我需要插入一个空项目作为数据数组中的第一项,该数据将被数据绑定到下拉列表。 My code looks like this:我的代码如下所示:

      let suppliers = response.data[0];
      let defaultSupplier = [{ SupplierId:0, ContactFirstName:''}];
      suppliers = [...defaultSupplier, suppliers];

I was thinking that this code would initialize my array with a default item, and then I could simply spread the retrieved suppliers data into this array.我在想这段代码会用一个默认项目初始化我的数组,然后我可以简单地将检索到的供应商数据传播到这个数组中。 However, the result of this approach is that I have an array where defaultSupplier is the first item in the array and then the second item in the array is an array of the retrieved supplier data.但是,这种方法的结果是我有一个数组,其中 defaultSupplier 是数组中的第一项,然后数组中的第二项是检索到的供应商数据的数组。 What approach do I need to take so that the retrieved suppliers data is appended at the same level as the defaultSupplier?我需要采取什么方法才能将检索到的供应商数据附加到与 defaultSupplier 相同的级别?

You have to spread suppliers .你必须分散suppliers But you created new array defaultSupplier with one element and spread this one.但是你用一个元素创建了新的数组defaultSupplier并传播了这个元素。 Correct variant:正确的变体:

let suppliers = response.data[0]; // array
let defaultSupplier = { SupplierId:0, ContactFirstName:''};
suppliers = [defaultSupplier, ...suppliers]; // spread array suppliers

defaultSupplier and supplier are both array of objects. defaultSuppliersupplier都是对象数组。

so, you need to spread both arrays into new array like this所以,你需要像这样将两个数组传播到新数组中

 suppliers = [...defaultSupplier, ...suppliers];

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

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