【问题标题】:How to get ID from JSON object in react.js ES6?如何从 react.js ES6 中的 JSON 对象获取 ID?
【发布时间】:2017-08-09 12:46:37
【问题描述】:

我有一个 JSON 对象的一维数组。在这些对象中的每一个中,都有一些与之关联的属性,例如姓名、身份证、地址等
我想从 react.js ES6 中的这个 JSON 数组中获取所有对象的 ID。
任何人都可以帮我做吗?

if(entities.length > 0) {
      let assignees = [];
      entities.map(id => {
        this.props.entities.map(entity => {
          if (id === entity.id) {
            assignees.push(entity.name);
            assignees.push(<br />);
          } else if (id !== entity.id && entities.indexOf(entity.id) !== -1) {
            console.log(entities.indexOf(entity.id));
            console.log("[");
            console.log(id);
            console.log(entity.id);
            console.log("]");
            assignees.push('Unknown');
            assignees.push(<br />);
          }
        });
      });
      return assignees;
    } else {
      return(
        <span>Unassigned</span>
      );
    }

【问题讨论】:

  • 你能告诉我们你到目前为止做了什么吗?谢谢
  • 也向我们展示对象..如果您不帮助我们理解,我们将无法帮助您。
  • if(entities.length > 0) { 让受让人= []; entity.map(id => { this.props.entities.map(entity => { if (id === entity.id) { assignees.push(entity.name); assignees.push(
    ); } else if (id !== entity.id && entities.indexOf(entity.id) !== -1) { assignees.push('Unknown'); assignees.push(
    ); } }); });返回受让人; } else { return( 未分配 ); }
  • 你能告诉我们你的json吗?
  • 请查看更新后的问题。 @SGN

标签: javascript reactjs react-redux


【解决方案1】:

let entities = [];
let assignees = [];

// create data for test

for (var i = 0; i < 10; i++) {
  entities.push({
    ID: Math.random() * 100
  });
}
entities.reduce((prev, crt) => {
    prev.push(crt.ID);
    return prev;
  },
  assignees);

console.log('Assignees', assignees);

这里

【讨论】:

    【解决方案2】:

    迭代您的对象数组并将 ID 推送到新数组中。

    var json_entities = [{ id: 1, ... }, { id: 2, ... }];
    var ids = [];
    json_entities.forEach( function(entity) {
        ids.push(entity.id);
    });
    

    亲切的问候

    【讨论】:

      【解决方案3】:

      处理此问题的首选函数式方法是使用map

      const ids = this.props.entities.map(entity => entity.id);
      

      【讨论】:

        猜你喜欢
        • 2018-06-17
        • 2015-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多