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
272 views
in Technique[技术] by (71.8m points)

javascript - updating object does not show the new property

the code in the example works fine but in my codes it doesn't

I`m trying to update object with a new property

 const overrides = {paths:{"/":{}}}
 const aItems = [{endpoint:"/test"}]
 const mockOverrides = JSON.parse(JSON.stringify(overrides));

 aItems.forEach(({endpoint}) => {
    if (!mockOverrides.paths[endpoint]) {
      mockOverrides.paths[endpoint] = {};
    }
    console.log(mockOverrides); // result {paths:{"/":{}}} expected {paths:{"/":{}, "/test":{}}}
    console.log(mockOverrides.paths[endpoint]) // result is  {}  twice
})

as you can see the property is not displayed in the output but is somehow exist why this happening?


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

1 Answer

0 votes
by (71.8m points)

After adding a ) to the end of the foreach method, it appears to be working fine:

 const overrides = {paths:{"/":{}}}
 const aItems = [{endpoint:"/test"}]
 const mockOverrides = JSON.parse(JSON.stringify(overrides));

 aItems.forEach(({endpoint}) => {
    if (!mockOverrides.paths[endpoint]) {
      mockOverrides.paths[endpoint] = {};
    }
    console.log(mockOverrides); // result {paths:{"/":{}}} expected {paths:{"/":{}, "/test":{}}}
    console.log(mockOverrides.paths[endpoint]) // result is  {}  twice
});

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

...