简体   繁体   English

在 map function ES6 中添加 1 个额外的 object

[英]Adding 1 additional object to the map function ES6

I have a code in place which looks like this -我有一个看起来像这样的代码 -

 mapFn={response => (response.data && response.data.map(secret => ({
                  label: secret.secretName,
                  value: secret.id
                })))}

I need to add one more additional object to response.data before it maps and sets it tp mapFn.我需要在 response.data 映射和设置它之前再添加一个 object 到 tp mapFn。 So I tried something like -所以我尝试了类似的东西 -

 mapFn={response => (response.data &&
                response.data.append({label: "Select Vault ID", value: "value"})
                && response.data.map(secret => ({
                  label: secret.secretName,
                  value: secret.id
                })))}

But I am getting an error as -但我收到一个错误 -

TS2339: Property 'append' does not exist on type 'SecretSummary[]

response.data is an array. response.data是一个数组。 Arrays don't have an .append method. Arrays 没有.append方法。 They do have a .push method, but it returns a number, rather than the array (and it mutates, which is forbidden in React).他们确实有一个.push方法,但它返回一个数字,而不是数组(并且它会发生变异,这在 React 中是被禁止的)。 Another issue is that the object you're adding has a label and value property - which sounds like something that should be added after mapping, not before mapping.另一个问题是您要添加的 object 有一个labelvalue属性——这听起来像是应该映射之后而不是在映射之前添加的东西。

Spread the mapped into a new array, and list the object you want to add at the end.将mapped展开到一个新的数组中,最后列出你要添加的object。

mapFn = {
    response => response.data &&
        [
            ...response.data.map(secret => ({
                label: secret.secretName,
                value: secret.id
            })),
            { label: "Select Vault ID", value: "value" }
        ]
}

(If you wanted to add the object before mapping, you'd probably want to use the secretName and id properties when defining the object instead, because otherwise calling the .map callback with the object wouldn't make sense.) (如果你想在映射之前添加 object,你可能想在定义 object 时使用secretNameid属性,否则使用 object 调用.map回调将没有意义。)

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

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