gpt4 book ai didi

javascript - 包含对象数组和字符串数组的对象

转载 作者:行者123 更新时间:2023-12-03 00:24:27 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 is the longest", "ref": "option2a"}
],
array2: [
"arrayItem1",
"array Item 2"
]
}

该对象包含对象数组和字符串数组。我想遍历每个具有标签的对象并返回最长的标签。在前面的示例中,预期输出 id:

“something5 是最长的”。

我尝试过以下方法:

function getLongest(object, key) {
return Object.values(object).reduce((l, v) => {
if (object.hasOwnProperty(key)) {
if (key in v)
return Math.max(l, v[key].length);
if (v && typeof v === 'object')
return Math.max(l, getLongest(v, key));
return l;
}
}, 0);
}

但是,这给了我一个错误,因为它找不到 array2 中项目的属性 label

最佳答案

这里有一种方法,它在 Object.Values() 上使用 anidated reduce() 方法:

var obj = {
"array1": [
{"label": "something1", "ref": "option2a"},
{"label": "something2", "ref": "option2b"},
{"label": "something3", "ref": "option2ahgf"},
{"label": "something4", "ref": "option2a"},
{"label": "I'm not the longest", "ref": "option2a"}
],
array2: [
"arrayItem1",
{"label": "something5 is the longest", "ref": "option2a"},
"array Item 2"
],
array3: [
{"label": "somethingX", "ref": "option2X"},
{"label": "somethingY", "ref": "option2Y"}
]
}

const getLongest = (obj, key) =>
{
let r = Object.values(obj).reduce((res, curr) =>
{
if (!Array.isArray(curr))
return res;

let newMax = curr.reduce(
(r, c) => c[[key]] && (c[[key]].length > r.length) ? c[[key]] : r,
""
);

res = newMax.length > res.length ? newMax : res;
return res;

}, "");

return r;
}

console.log(getLongest(obj, "label"));
console.log(getLongest(obj, "ref"));

关于javascript - 包含对象数组和字符串数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54152210/

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