簡體   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