【问题标题】:create an object using forEach使用 forEach 创建一个对象
【发布时间】:2020-10-08 13:23:16
【问题描述】:

根据 graphql 查询返回的数据,我想创建一个像这样的对象:

const DATA = [
    {
        id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
        imageUrl: defaultUrl,
        name: 'Johann',
    },
    {
        id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
        imageUrl: defaultUrl,
        name: 'Lars',
    },
    {
        id: '58694a0f-3da1-471f-bd96-145571e29d72',
        imageUrl: defaultUrl,
        name: 'Sarah',
    },
];

但是,我不明白如何遍历数据并从中创建对象。例如,通过这样做,我可以将所有名字提取到一个数组中:

var friendNames = new Array();

if (data !== null && data !== undefined) {
    data.users.nodes[0].userRelations.forEach((relation: UserRelation) => {
        friendNames.push(relation.relatedUser.firstName);
    });
}

但是,除了名字之外,我还想添加 id 和硬编码链接(现在所有项目都相同)。但是我怎样才能让我的数据的形状类似于 const DATA

【问题讨论】:

  • friendNames.push({name:relation.relatedUser.firstName,other:'value'});

标签: javascript arrays reactjs typescript react-native


【解决方案1】:

您正在尝试基于另一个数组创建一个新数组。

对于这个特殊用途,函数map 是最适合的(mapforEach 的表亲)。

对于userRelations数组的每个条目,我们将在一个全新的数组中创建一个新条目。

const data = {
  users: {
    nodes: [{
      userRelations: [{
        relatedUser: {
          firstName: 'Johann',
        },
      }, {
        relatedUser: {
          firstName: 'Lars',
        },
      }, {
        relatedUser: {
          firstName: 'Paul',
        },
      }],
    }],
  },
};

const myFormattedData = data.users.nodes[0].userRelations.map(x => ({
  id: 'myId',
  imageUrl: 'myUrl',
  name: x.relatedUser.firstName,
}));

console.log(myFormattedData);

替代语法:

const data = {
  users: {
    nodes: [{
      userRelations: [{
        relatedUser: {
          firstName: 'Johann',
        },
      }, {
        relatedUser: {
          firstName: 'Lars',
        },
      }, {
        relatedUser: {
          firstName: 'Paul',
        },
      }],
    }],
  },
};

const id = 'myId';
const imageUrl = 'myUrl';

const myFormattedData = data.users.nodes[0].userRelations.map(({
  relatedUser: {
    firstName: name,
  },
}) => ({
  id,
  imageUrl,
  name,
}));

console.log(myFormattedData);

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    相关资源
    最近更新 更多