【问题标题】:How to automatically move JSON data depending on Boolean value [duplicate]如何根据布尔值自动移动 JSON 数据 [重复]
【发布时间】:2020-03-23 01:41:06
【问题描述】:

我有一个 JSON 文件:

 [
  {
   "id": 1,
   "color": "Blue",
   "availability": false
  },
  {
   "id": 2,
   "color": "Pink",
   "availability": true
  }
 ]

我想要实现的是让带有“availability : true”的 JSON 自动出现在“availability : false”之上。使粉红色出现在蓝色上方,如下所示:

到目前为止,这是我的代码,它只是按照与 JSON 文件相同的顺序显示它们:

import React, { Component } from 'react';
import './styles.css'

class GetOnlinePosts extends Component {
constructor(props){
    super(props);
    this.state = {
        error : null,
        isLoaded : false,
        posts : []          
    };
}
componentDidMount(){
    fetch("https://api.myjson.com")
    .then( response => response.json())
    .then(
        (result) => {
            this.setState({
                isLoaded : true,
                posts : result
            });
        },
        (error) => {
            this.setState({
                isLoaded: true,
                error
            })
        },
    )
}
render() {
    const {error, isLoaded, posts} = this.state;
    if(error){
        return <div>Error in loading</div>
    }else if (!isLoaded) {
        return <div>Loading ...</div>
    }else{
        return(
            <div>
                <div className="tiles">
                {
                    posts.map(post => (
                        <div key={post.id}>
                            <div className="tile">
                                <p className="color">{post.color}</p>
                            </div> 
                       </div>
                      ))
                    }
                </div>
            </div>
        );
    }
  }
}

export default GetOnlinePosts;

我不确定如何实现这一点,并且到目前为止一直在努力寻找任何建议,所以任何帮助都会很棒。

【问题讨论】:

  • .sort()他们先在availability上,然后再打电话给.map()
  • 也许你可以将这个对象数组分离到另外两个数组中,一个是可用的,另一个是不可用的(使用mapfilter 或类似的东西),然后运行可用的优先,这样“粉红色”的将首先出现。或者只是.sortavailability的数组@
  • 在从 componentDidMount 函数返回之前,您需要 .sort 您的数据。
  • [...posts].sort((a, b) =&gt; b.availability - a.availability).map(...)

标签: javascript json reactjs


【解决方案1】:

var data = [{
    "id": 1,
    "color": "Blue",
    "availability": false
  },
  {
    "id": 2,
    "color": "Pink",
    "availability": true
  },
  {
    "id": 3,
    "color": "Pink",
    "availability": true
  },
  {
    "id": 4,
    "color": "Pink",
    "availability": false
  }, {
    "id": 5,
    "color": "Pink",
    "availability": true
  }
]
//unordered
data.sort(val => val.availability ? -1 : 1) //simple one line sort function for boolean
console.log(data);

// ordered based on your default array order
data = [{
    "id": 1,
    "color": "Blue",
    "availability": false
  },
  {
    "id": 2,
    "color": "Pink",
    "availability": true
  },
  {
    "id": 3,
    "color": "Pink",
    "availability": true
  },
  {
    "id": 4,
    "color": "Pink",
    "availability": false
  }, {
    "id": 5,
    "color": "Pink",
    "availability": true
  }
]

data.sort((a, b) => b.availability - a.availability);
console.log(data);

【讨论】:

  • 这不会保持所有true值的相对顺序
  • 相对顺序是什么意思,能具体点吗?
  • 为每个对象提供不同的id。结果数组中的true 值的顺序与原始数组中的顺序不同。 sort 的回调有 2 个参数。这里只考虑第一个参数,导致排序不一致
  • 好的,你想保留订单吗?...
  • 如果你给对象 id 从 1 到 5,那么 5 位于顶部(在 Chrome 中)。它在排序后的数组中应该是 2-3-5,因为这就是对象在输入中的放置方式。 .sort((a, b) =&gt; b.availability - a.availability) 会保持原来的相对顺序
【解决方案2】:

你可以过滤这两个集合,创建一个新数组然后渲染它。

import React, { Component } from 'react';
import './styles.css'

class GetOnlinePosts extends Component {
constructor(props){
    super(props);
    this.state = {
        error : null,
        isLoaded : false,
        posts : []          
    };
}
componentDidMount(){
    fetch("https://api.myjson.com")
    .then( response => response.json())
    .then(
        (result) => {
            this.setState({
                isLoaded : true,
                posts : result
            });
        },
        (error) => {
            this.setState({
                isLoaded: true,
                error
            })
        },
    )
}
render() {
    const {error, isLoaded, posts} = this.state;
    const orderedPosts = [...posts.filter((post) => post.availability), ...posts.filter((post) => !post.availability)]
    if(error){
        return <div>Error in loading</div>
    }else if (!isLoaded) {
        return <div>Loading ...</div>
    }else{
        return(
            <div>
                <div className="tiles">
                {
                    orderedPosts.map(post => (
                        <div key={post.id}>
                            <div className="tile">
                                <p className="color">{post.color}</p>
                            </div> 
                       </div>
                      ))
                    }
                </div>
            </div>
        );
    }
  }
}

export default GetOnlinePosts;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多