简体   繁体   English

在 React 中,如何使用“map”将对象数组转换为新的对象数组?

[英]In React, how can I use “map” to transform an array of objects into a new array of objects?

I have a simple question regarding my React 16.10.0.我有一个关于我的 React 16.10.0 的简单问题。 How do I transform my array into another array of objects?如何将我的数组转换为另一个对象数组? I have an array of objects that have attributes我有一组具有属性的对象

id
name

And I want to convert that array to another array with attributes我想将该数组转换为另一个具有属性的数组

id
text

So I tried所以我尝试了

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
     
    const tags = props.values.map(result => 
      {
        id: result.id,
        text: result.name
      });

but the compiler is complaining that a ";"但编译器抱怨“;” is expected on the "text:" line.预计在“文本:”行上。

Javascript is interpreting the {... } as a block of code instead of an object literal. Javascript 将{... }解释为代码块,而不是 object 文字。 An easy way to get around that is to just add parenthesis around the object, as in the following:一个简单的解决方法是在 object 周围添加括号,如下所示:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);

        const tags = props.values.map(result => 
            ({
                id: result.id,
                text: result.name
            }));

I think you're mixed up because of the implied return not working when returning an object.我认为您混淆了,因为在返回 object 时隐含的return不起作用。

There's two ways to return from an arrow function:从箭头返回 function 有两种方法:

Explicit return (block body)显式返回(块体)

() => {
  return 'something';
}

or Implicit return (concise body)或隐式返回(简洁的正文)

() => 'something';
() => ('something')

You're attempting to use implicit return, but you're returning an object, so the syntax conflicts with your expectation.您尝试使用隐式返回,但返回的是 object,因此语法与您的预期冲突。

result => 
{
  id: result.id,
  text: result.name
});

This is not an object, but a function body.这不是 object,而是 function 主体。 The function body is invalid syntax leading to the error. function 正文是导致错误的无效语法。

You can fix this by using parenthesis, or by manually returning:您可以通过使用括号或手动返回来解决此问题:

result => 
({
  id: result.id,
  text: result.name
};
result => {
  return {
    id: result.id,
    text: result.name
}};

For reference: check out the section "Returning object literals" in the docs for arrow functions ,供参考:查看箭头函数文档中的“返回 object 文字”部分,

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

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