gpt4 book ai didi

javascript - 如何在对象数组中找到具有最长字符长度的对象键

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:42 27 4
gpt4 key购买 nike

假设我有一个像这样的对象集合

var collection = [
{
name:"John",
age:12,
location:"Califonia",
gender:"Male"
},
{
name:"Jane",
age:18,
location:"New york",
gender:"Female"
}
]

很明显“location”是字符长度最长的对象键。

但是我怎样才能动态地得到这个,因为我不知道如何提前构建集合。

最佳答案

具有这些功能:

/**
* Get the longest key in an object.
*/
function longestKey(obj) {
return Object.keys(obj).reduce(function(all, current) {
return all.length > current.length ? all : current;
});
}

/**
* Get the object with the longest key from array of objects.
*/
function longestKeyObj(arr) {
return arr.reduce(function(all, current) {
return longestKey(all).length > longestKey(current).length ? all : current;
});
}

你可以这样做:

const me = {
name: 'nabil',
occupation: 'programming',
dob: '1984-12-28',
};

const you = {
longestKey: 'blah!',
};

console.log('The object is: ', longestKeyObj([me, you]));
console.log('The key is: ', longestKey(longestKeyObj([me, you])));

哪些输出:

The object is: { longestKey: 'blah!' }

The key is: longestKey

演示:https://repl.it/@kadimi/longestKey

关于javascript - 如何在对象数组中找到具有最长字符长度的对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32308846/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com