迭代嵌套对象以找到关键属性并返回该对象 - Javascript

用户1234

我有一个父对象和多个子对象,这是结构:

parent: {
  child1: {
    "aaa": {values: [], type: "string", title: "AAA"},
    "bbb": {values: [], type: "string", title: "BBB"},
    "ccc": {values: [], type: "string", title: "CCC"},
    "ddd": {values: [], type: "string", title: "DDD"}
  },
  child2: {
    "eee": {values: [], type: "string", title: "EEE"},
    "fff": {values: [], type: "string", title: "FFF"},
    "ggg": {values: [], type: "string", title: "GGG"},
    "hhh": {values: [], type: "string", title: "HHH"}
  },
  child3: {
    "iii": {values: [], type: "string", title: "III"},
    "jjj": {values: [], type: "string", title: "JJJ"},
    "kkk": {values: [], type: "string", title: "KKK"},
    "lll": {values: [], type: "string", title: "LLL"}
  }
}

现在我有一个函数,它返回子对象的键的子值之一。前任:

function childVal() {
  //do somehting 
  return "aaa";
}

现在根据这个值,我想获取整个子对象,例如:如果返回值是"bbb",我希望返回具有"bbb"的对象,在这种情况下是child1

因此输出以下值:

"aaa": return child1;
"ggg": return child2;
"bbb": return child1;
"lll": return child3;

这可能吗?

萨沙

function parentFilter(parent, myFilter) {
    return Object.values(parent).filter(child => Object.keys(child).some(key => key===myFilter));
}

let parent = {
       child1: {
      "aaa": {values: [], type: "string", title: "AAA"},
      "bbb": {values: [], type: "string", title: "BBB"},
      "ccc": {values: [], type: "string", title: "CCC"},
     "ddd": {values: [], type: "string", title: "DDD"}
    },
      child2: {
    "eee": {values: [], type: "string", title: "EEE"},
      "fff": {values: [], type: "string", title: "FFF"},
      "ggg": {values: [], type: "string", title: "GGG"},
     "hhh": {values: [], type: "string", title: "HHH"}
    },
      child3: {
    "iii": {values: [], type: "string", title: "III"},
      "jjj": {values: [], type: "string", title: "JJJ"},
      "kkk": {values: [], type: "string", title: "KKK"},
     "lll": {values: [], type: "string", title: "LLL"}
    }
 };
    
console.log(parentFilter(parent, 'aaa'));
console.log('-----------');
console.log(parentFilter(parent, 'ggg'));
console.log('-----------');
console.log(parentFilter(parent, 'bbb'));
console.log('-----------');
console.log(parentFilter(parent, 'lll'));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章