按照参数对嵌套对象进行排序的JS
创始人
2024-08-23 13:30:14
0

以下是一个按照参数对嵌套对象进行排序的示例代码:

// 嵌套对象数组
const objArray = [
  { name: "John", age: 30, nestedObj: { score: 80 } },
  { name: "Amy", age: 28, nestedObj: { score: 90 } },
  { name: "Bob", age: 35, nestedObj: { score: 75 } }
];

// 按照参数对嵌套对象进行排序函数
function sortByParameter(arr, parameter) {
  return arr.sort((a, b) => {
    // 使用参数路径来获取嵌套对象的值
    const aValue = getNestedValue(a, parameter);
    const bValue = getNestedValue(b, parameter);
    
    // 比较两个对象的值并返回排序结果
    if (aValue < bValue) {
      return -1;
    } else if (aValue > bValue) {
      return 1;
    } else {
      return 0;
    }
  });
}

// 递归地获取嵌套对象的值
function getNestedValue(obj, path) {
  const keys = path.split(".");
  let value = obj;
  
  for (let key of keys) {
    value = value[key];
  }
  
  return value;
}

// 按照嵌套对象的score属性进行排序
const sortedArray = sortByParameter(objArray, "nestedObj.score");
console.log(sortedArray);

上述代码中,sortByParameter函数接受一个嵌套对象数组和一个参数路径作为参数。它使用getNestedValue函数来获取嵌套对象的值,并使用Array.prototype.sort方法对数组进行排序。getNestedValue函数使用递归的方式获取嵌套对象的值,将参数路径拆分成键数组,并通过循环迭代嵌套对象来获取最终的值。

在示例中,我们将嵌套对象数组按照nestedObj.score进行排序,并将排序结果打印到控制台上。

相关内容

热门资讯

出现新变化!wepoker有没... 出现新变化!wepoker有没有透视方法,提高微乐运气的方法,教你脚本(真实有挂)-哔哩哔哩1、全新...
透视解密!wpk俱乐部怎么作必... 透视解密!wpk俱乐部怎么作必弊,wpk插件(透视)其实真的是有方法(哔哩哔哩)运辅助工具,进入游戏...
无独有偶!hh poker辅助... 无独有偶!hh poker辅助器先试用,微信微乐自建房脚本免费下载,推荐透视(有挂头条)-哔哩哔哩1...
脚本推荐!aapoker免费透... 脚本推荐!aapoker免费透视脚本,aapoker真的假的(透视)都是是真的脚本(哔哩哔哩)1、下...
反观!wepokerplus万... 反观!wepokerplus万能挂,微乐小程序自建房透视,辅助透视(有挂教程)-哔哩哔哩1、实时we...
脚本总结!hhpoker辅助挂... 脚本总结!hhpoker辅助挂下载,hhpoker有没有辅助(透视)确实真的是有软件(哔哩哔哩)1、...
今年以来!wepoker黑侠辅... 今年以来!wepoker黑侠辅助器正版下载,微乐辅助脚本,解迷透视(有挂教学)-哔哩哔哩1、wepo...
围绕透视问题!aa poker... 围绕透视问题!aa poker透视软件,微乐智能辅助真的假的,专业脚本(有挂总结)-哔哩哔哩1、每一...
透视科普!aapoker插件下... 透视科普!aapoker插件下载,aapoker透视脚本(透视)原来是有挂(哔哩哔哩)1、这是跨平台...
透视软件!hhpoker必备开... 透视软件!hhpoker必备开挂,微信小程序微乐破解器2025,科普脚本(有挂技巧)-哔哩哔哩1)h...