Javascript 如何在Js中按键过滤和排序对象?
我正在尝试按React应用程序中的键对对象进行排序。我有一个对象(数据)和字符串值(someString),我需要根据这个someString的值按照相同的顺序按其键对我的obj进行排序和过滤。到目前为止,我能够根据someString中的键值对对象进行筛选和排序,问题是我不知道如何在按键排序后显示对象的值,现在只显示键 我的代码是:Javascript 如何在Js中按键过滤和排序对象?,javascript,reactjs,sorting,object,filter,Javascript,Reactjs,Sorting,Object,Filter,我正在尝试按React应用程序中的键对对象进行排序。我有一个对象(数据)和字符串值(someString),我需要根据这个someString的值按照相同的顺序按其键对我的obj进行排序和过滤。到目前为止,我能够根据someString中的键值对对象进行筛选和排序,问题是我不知道如何在按键排序后显示对象的值,现在只显示键 我的代码是: import "./styles.css"; export default function App() { const data =
import "./styles.css";
export default function App() {
const data = {
info: {
name: "Jane Smith",
info: "26 years old"
},
newInfo: {
name: "John Smith",
info: "35 years old"
},
updatedInfo: {
name: "James Smith",
info: "45 years old"
},
latestUpdate: {
name: "J D",
info: "23 years old"
}
};
let someString = "newInfo,latestUpdate,updatedInfo";
let newData = Object.keys(data)?.filter((i) => someString.includes(i));
const sorted = newData.sort((a, b) => {
const aIndex = someString.indexOf(a);
const bIndex = someString.indexOf(b);
return aIndex - bIndex;
});
console.log(sorted, "sorted");
return <div className="App">{sorted}</div>;
}
但我还需要排序对象的值,如下所示:
newInfo: {
name: "John Smith",
info: "35 years old"
},
latestUpdate: {
name: "J D",
info: "23 years old"
},
updatedInfo: {
name: "James Smith",
info: "45 years old"
},
排序后,将它们转换为带有
对象的对象。fromEntries
:
const数据={
信息:{
姓名:“简·史密斯”,
信息:“26岁”
},
新信息:{
姓名:“约翰·史密斯”,
信息:“35岁”
},
更新信息:{
姓名:“詹姆斯·史密斯”,
信息:“45岁”
},
最晚日期:{
姓名:“J D”,
信息:“23岁”
}
};
const someString=“newInfo,latestUpdate,updateinfo”;
constkeys=Object.keys(data.filter)(key=>someString.includes(key));
const sortedObj=Object.fromEntries(
钥匙
.sort((a,b)=>someString.indexOf(a)-someString.indexOf(b))
.map(键=>[key,数据[key]])
);
控制台日志(sortedObj)代码>
newInfo: {
name: "John Smith",
info: "35 years old"
},
latestUpdate: {
name: "J D",
info: "23 years old"
},
updatedInfo: {
name: "James Smith",
info: "45 years old"
},