gpt4 book ai didi

javascript - 对象数组的对象。获取具有相同属性的所有值的长度

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:20 25 4
gpt4 key购买 nike

我有一个看起来像这样的对象:

    var obj = {
"array1": [
{
"label": "something1",
"ref": "option2a"
},
{
"label": "something2",
"ref": "option2b"
},
{
"label": "something3",
"ref": "option2a"
},
{
"label": "something4",
"ref": "option2a"
},
{
"label": "something5",
"ref": "option2a"
}
],
"array2": [
{
"label": "something6 is the longest label",
"ref": "option3a"
},
{
"label": "Other",
"ref": "option3b"
}
]
}

我想得到最长标签的长度。在这种情况下,我想返回 17。因为最长的标签是“somethinglongest”,长度为 17。

最佳答案

  • 使用 .concat()Object.values() 获取包含所有对象的单个数组。
  • 对包含字符串长度的数组使用 .map()
  • 最后使用.reduce() 得到最长字符串的长度。

let data = {
"array1": [
{"label": "something1", "ref": "option2a"},
{"label": "something2", "ref": "option2b"},
{"label": "something3", "ref": "option2a"},
{"label": "something4", "ref": "option2a"},
{"label": "something5", "ref": "option2a"}
],
"array2": [
{"label": "somethinglongest", "ref": "option3a"},
{"label": "Other", "ref": "option3b"}
]
};

let reducer = arr => [].concat(...Object.values(arr))
.map(({ label }) => label.length)
.reduce((r, c) => r > c ? r : c);

console.log(reducer(data));

关于javascript - 对象数组的对象。获取具有相同属性的所有值的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134498/

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