I have one javascript array and one object. Need help to sort javascript object keys based on the order number in another array
In subgroup array, I have name, order number. Need to sort Offerings keys based on that order number
const subgroup = [
{
"code": "6748",
"name": "test123",
"orderNumber": "0"
},
{
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}
]
const offerings = {
"customdata" : [
{
"code": "Audi",
"color": "black"
}
],
"test123" : [
{
"brand": "Audi",
"color": "black"
}
]
}
I believe this should work for you. I've added some comments in the code that should hopefully do an okay job of explaining what is happening.
var subgroup = [{ "code": "6748", "name": "test123", "orderNumber": "0" }, { "code": "1234", "name": "customdata", "orderNumber": "1" }]; var offerings = { "customdata": [{ "code": "Audi", "color": "black" }], "test123": [{ "brand": "Audi", "color": "black" }] } function sortObjectFromArray(refArray, sortObject, orderKey = 'order', linkKey = 'key') { // Get copy of refArray let reference = refArray.slice(); // Sort sortObject [ into an array at this point ] let sorted = []; for (let key in sortObject) { // Searches the refArray for the linkKey, and returns the intended index let index = reference.find((item) => item[linkKey] === key)[orderKey]; // Places the sortObject's value in the correct index of the 'sorted' Array sorted[parseInt(index)] = [key, sortObject[key]]; }; // Return an object, created from previous 'sorted' Array return sorted.reduce((obj, [key, value]) => { obj[key] = value; return obj; }, {}); }; offerings = sortObjectFromArray(subgroup, offerings, 'orderNumber', 'name'); console.log(offerings);
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.