gpt4 book ai didi

javascript - 如何根据 bool 值自动移动 JSON 数据

转载 作者:行者123 更新时间:2023-12-02 22:25:58 26 4
gpt4 key购买 nike

我有一个 JSON 文件:

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

我想要实现的是带有“availability : true”的 JSON 自动出现在“availability : false”上方。这样粉色就会出现在蓝色上方,如下所示:

enter image description here

这是我到目前为止的代码,它只是按照与 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;

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

最佳答案

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);

关于javascript - 如何根据 bool 值自动移动 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59071227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com