Javascript嵌套对象遍历 [英] Javascript nested object traversal

查看:47
本文介绍了Javascript嵌套对象遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个代码,我必须遍历嵌套对象并在单个字符串中返回所有值.例如,如果这是输入:

I'm doing a code where I have to traverse a nested object and return all the values in a single string. For example, if this is the input:

var obj = {
name: "root",
contents: [
  {
    name: "A",
    contents: [
      {
        name: "fileA1",
        contents: ["Hello!"]
      }
    ]
  },
  {
    name: "B",
    contents: [
      {
        name: "dirB1",
        contents: [
          {
            name: "fileB1.1",
            contents: ["Hello!"]
          }
        ]
      }
    ]
  }
]
};

输出应该是:

root
A
fileA1
Hello!
B
dirB1
fileB1.1
Hello!

我的代码是:

function toArray(obj) {
var result = '';
for (const prop in obj) {
    const value = obj[prop];
    if (typeof value === 'object') {
        result+=(toArray(value)); 
    }
    else {
        result+=(value);
    }
}
//console.log(result);
return result;
}

但是当我运行它时,它返回以下字符串:

But when I run it, it returns the following string:

Hello!
fileA1undefined
undefined
Aundefined
Hello!
fileB1.1undefined
undefined
dirB1undefined
undefined
Bundefined
undefinedundefined
rootundefined

为什么我的值出现未定义",我该如何解决?

Why am I getting the "undefined" with the values and how can I fix this?

推荐答案

你可以使用 flatMapObject.values() 像这样:

You could use flatMap and Object.values() like this:

var obj = {name:"root",contents:[{name:"A",contents:[{name:"fileA1",contents:["Hello!"]}]},{name:"B",contents:[{name:"dirB1",contents:[{name:"fileB1.1",contents:["Hello!"]}]}]}]}

const getValues = o =>
  Object.values(o).flatMap(v => typeof(v) === 'object' ? getValues(v) : v)

console.log(getValues(obj).join('\n'))

如果您将 \n 添加到 result += value,您的代码将返回所需的结果:

If you add a \n to result += value, your code returns the desired result:

function toArray(obj) {
  var result = '';
  for (const prop in obj) {
    const value = obj[prop];
    if (typeof value === 'object') {
      result += toArray(value);
    } else {
      result += value + '\n';
    }
  }
  return result;
}

var obj = {name:"root",contents:[{name:"A",contents:[{name:"fileA1",contents:["Hello!"]}]},{name:"B",contents:[{name:"dirB1",contents:[{name:"fileB1.1",contents:["Hello!"]}]}]}]}

console.log(toArray(obj))

这篇关于Javascript嵌套对象遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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