繁体   English   中英

键未使用 javascript 在 JSON 数组中排序

[英]key is not sorted in JSON array using javascript

在此,我试图按partNo对数据进行排序,并且它与此完美排序,但我的问题是表的第一列没有与列的 rest 排序 sr No必须与所有其他列一起排序

这里sr No是未与其他列排序的键

 let productDetails = { "10": [{ id: "1", partNo: "100", productName: "bag", size: "30", color: ["Blue"], description: "sky bags ", }], "20": [{ id: "2", partNo: "15", productName: "bottle", size: "10", color: ["Green", "Orange"], description: "plastic and still", }], "30": [{ id: "4", partNo: "25", productName: "lunchbox", size: "20", color: ["Blue", "Red"], description: "fresh food", }], "40": [{ id: "3", partNo: "45", productName: "pen", size: "10", color: ["Red", "Blue"], description: "gel pen ", }] }; /** * This function displays the data in the table */ function displayData() { objectArray = Object.values(productDetails); display(objectArray); } function display(productStore) { messageTable(" "); let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><tr><th>sr No</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th></tr>"; for (var key in productDetails) { for (var weight in productDetails[key]) { table += "<tr><td>" + key + "</td>"; table += "<td>" + productDetails[key][weight].id + "</td>"; table += "<td>" + productDetails[key][weight].partNo + "</td>"; table += "<td>" + productDetails[key][weight].productName + "</td>"; table += "<td>" + productDetails[key][weight].size + "</td>"; table += "<td>" + productDetails[key][weight].color + "</td>"; table += "<td>" + productDetails[key][weight].description + "</td>"; } } messageTable(table); } /** * function to sort an array by part No */ function sortByPartNo() { let arr = []; item = Object.keys(productDetails) console.log(item) item.forEach(function (index) { productDetails[index].forEach(function (indexA) { arr.push(indexA); }); }) arr.sort(function (first, second) { return parseFloat(first.partNo) - parseFloat(second.partNo); }); console.log(arr) printArray(arr, item) } /** * function to print array in the table */ function printArray(arr, item) { messageTable(" "); let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><tr><th>sr No</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th></tr>"; for (let key in arr) { table += "<tr><td>" + item[key] + "</td>"; table += "<td>" + arr[key].id + "</td>"; table += "<td>" + arr[key].partNo + "</td>"; table += "<td>" + arr[key].productName + "</td>"; table += "<td>" + arr[key].size + "</td>"; table += "<td>" + arr[key].color + "</td>"; table += "<td>" + arr[key].description + "</td>"; } messageTable(table); } /** * function is to print the table */ function messageTable(data) { document.getElementById("messageTableA").innerHTML = data; } /** * this function is to print the message */ function message(message) { document.getElementById("demo").innerHTML = message; }
 <,DOCTYPE html> <html> <head> <style> th, td, p: input { font-family, Arial, Helvetica; sans-serif, } table, th: td { border; solid 1px #DDD: border-collapse; collapse: padding; 10px 10px: text-align; center: } th { font-weight; bold: } </style> </head> <body onload="displayData()"> <h2>Product Details;</h2> <form action=""> <input type="button" value="sortByPartNo" onclick="sortByPartNo();">&nbsp; <p id="result"></p> <p id="demo"></p> <p id="messageTableA"></p> </form> </body> </html>

go 有几种方法可以解决这个问题,但最简单的方法是从包含键和值的原始对象构造一个新对象。

即转这个:

{
  "10": [{
    "partNo": "100",
    "size": "30",
    // etc
  }],
  // ...
}

进入这个

[
  {
    "key": "10",
    "partNo": "100",
    "size": "30",
    // etc
  },
  // ...
]

或者,类似的东西也可以。 下面的具体代码示例中使用了类似的方法。

[
  {
    "key": "10",
    "value": {
      "partNo": "100",
      "size": "30",
      // etc
    },
  },
  // ...
]

基本上,我们只需要在执行 sort() 之前将所有相关信息捆绑在一起。 在我们排序之后,我们可以将捆绑的数据按原样传递给您的显示函数,或者我们可以将它们分成两个列表,但您愿意。

一个实际的简化示例:

 const data = { 1: { color: 'blue', size: 10, }, 2: { color: 'green', size: 50, }, 3: { color: 'yellow', size: 5, }, } // Object.entries() will reshape the data in a way that keeps keys and values together // then we.sort() based on size const sorted = ( Object.entries(data).sort((x, y) => x[1].size - y[1].size) ) console.log('sorted keys and values', sorted) // If you want, you can then split them back out into two separate array, like you had it: console.log('sorted keys', sorted.map(x => x[0])) console.log('sorted values', sorted.map(x => x[1]))

请参阅内容以了解此特定示例中使用的 Object.entries。

Scotty Jamison 最先做出回应,并给您很好地描述了选项和替代方案。 我敦促你接受他的回答。

但是,我认为我很好地提供了我为响应您的原始问题而开发的工作,该原始问题被错误地标记为重复(正如您在此处对您的问题的评论中提到的那样)。 这是 Scotty 的第一个提案的更完整版本,它将外键作为属性放置在数组条目中。

 // Just a convenience for building productDetails let pdVal = (id,no,name,size,colors,desc) => ({ id: id, partNo: no, productName: name, size: size, color: colors, description: desc }) let productDetails = { "10": [pdVal("1","100","bag","30",["Blue"],"sky bags ")], "20": [pdVal("2","15","bottle","10",["Green", "Orange"],"plastic and still")], "30": [pdVal("4","25","lunchbox","20",["Blue", "Red"],"fresh food")], "40": [pdVal("3","45","pen","10",["Red", "Blue"],"gel pen ")] }; function sortByPartNo() { let arr = []; for (let key of Object.keys(productDetails)) { let obj = productDetails[key][0]; arr.push(Object.assign({}, obj, {key})); } arr.sort((a,b) => parseFloat(a.partNo) - parseFloat(b.partNo)) printArray(arr); } function printArray(arr) { messageTable(" "); let table = ` <table border = 1 cellpadding = 10 > <th colspan=7 >Product Details</th> <tr> <th>sr No</th> <th>Product Id</th> <th>Part No</th> <th>Name</th> <th>Size</th> <th>Color</th> <th>Description</th> </tr> `; for (let item of arr) { console.log({arr}) table += "<tr><td>" + item.key + "</td>"; table += "<td>" + item.id + "</td>"; table += "<td>" + item.partNo + "</td>"; table += "<td>" + item.productName + "</td>"; table += "<td>" + item.size + "</td>"; table += "<td>" + item.color + "</td>"; table += "<td>" + item.description + "</td>"; } messageTable(table); } function messageTable(data) { document.getElementById("messageTableA").innerHTML = data; }
 <input type="button" value="sortByPartNo" onclick="sortByPartNo();">&nbsp; <p id="result"></p> <p id="demo"></p> <p id="messageTableA"></p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM