包含对象数组和字符串数组的对象 [英] Object containing arrays of objects and arrays of strings

查看:92
本文介绍了包含对象数组和字符串数组的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an object that looks like this:

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:

This object contains arrays of objects and arrays of strings. I would like to traverse through each object that has a label and return the longest label. In the previous example, the expected output id:

"something5 is the longest".

我尝试了以下操作:

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.

However this gives me an error because it cannot find the property label for the items in array2.

推荐答案

在这里,您有一种方法在Object.Values()上使用带注释的reduce()方法:

Here you have one approach that used anidated reduce() methods over the Object.Values():

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"));

这篇关于包含对象数组和字符串数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆