简体   繁体   中英

key is not sorted in JSON array using javascript

In this I am trying to sort the data by partNo and it is perfectly sorted with this, but my problem is that .sr No has to be sorted with all other columns

here sr No is a key which is not sorted with other columns

 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>

There's a couple ways to go about this, but the simplest would be to just construct a new objects from the original one that contains both the keys and values.

ie turn this:

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

into this

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

or alternatively, something like this works too. A similar approach is used in the concrete code example below.

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

Basically, we just need to bundle all the related information together before we do a sort(). After we sort, we can pass the bundled data as-is to your display functions, or we can separate them back into two lists, however you prefer.

A practical simplified example:

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

See this to learn about Object.entries, used in this particular example.

Scotty Jamison responded first and gave you a good description of options and alternatives. I urge you to accept his answer.

However, I figured I minus well provide my work that I had developed in response to your original question incorrectly marked as a duplicate (as you mention in the comments to your question here). It is a more fully worked out version of Scotty's first proposal, which places the outer key as a property inside the array entry.

 // 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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