Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

JS对象展平问题。想得到[{"a":12,"d":23},{"a":912,"d":923}]

let a=[{"a":12,b:{"d":23}},{"a":912,b:{"d":923}}]
let res = [{}]
    for (var index = 0; index < a.length; index += 1) {
      Object.keys(a[index]).forEach(key => {
        if (typeof a[index][key] === "object") {
          Object.keys(a[index][key]).forEach(
            innerKey => {res[index][innerKey] = a[index][key][innerKey]}
          )
        }else{
console.log(a[index][key])
          res[index][key] = a[index][key]
console.log(res)
        }
      })
    }

请问我想把a展平,为什么上面那样写数组的第一个对象出来了,可是第二个出错了。谢谢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你初始化只有一个空对象,到下一个对象也就是index为1的时候res里索引为1即res[1]=undefined,那你的else就报错了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...