Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - adding multiple properties to object in a loop

I think my question is easy but I dont understand why my solution doesnt work :( I'm trying to add to a new object some long properties using foreach loop but I'm getting the whole time error. Could someone please help me?

let i = 0;
const obj = {};
for (const item of read) {
  console.log(item.name);
  console.log(item.imageURL);
  obj['hits']['hits'] ='whyDosntWork';
  console.log(item.name);
  if (item.imageURL) {
    obj['hits']['hits'][i]['_source.ActiveChannelReleases'][0]['ImageExports'][0]['Resolutions'][0]['Url'] =getServerURL()+item.imageURL;
  } else {
    obj['hits']['hits'][i]['_source.ActiveChannelReleases'][0]['ImageExports'][0]['Resolutions'][0]['Url'] ='https://cdn3.iconfinder.com/data/icons/kitchen-glyph-black/2048/4834_-_Cookbook-512.png';
  }
  console.log(item.imageURL);
  i++;
}

I have an response and I want to mock it with my data

I wish to have for example an object that I can fill with data:

class ResponseController {
  constructor() {
    this.response = {
      'hits': {
        'hits': [{'_source.ActiveChannelReleases': [{'ImageExports': ['Resolutions']}],

        }],
      },
    };
  }
}
module.exports = ResponseController;

Will it work if I write

obj = new ResponseController();

and then I can easily add variables from the looo?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First this is a madness :).

Why is not working?

const obj = {};

you cannot do this obj['hits']['hits'] ='whyDosntWork'; due to obj['hist'] does not exists.

You need to do:

obj['hits'] = {}

and then obj['hits']['hits'] ='whyDosntWork';

And the same for the rest...

I cannot understand what do you want to do here:

obj['hits']['hits'][i]['_source.ActiveChannelReleases'][0]['ImageExports'][0]['Resolutions'][0]['Url']

But follow what I said before, you need to create each step the value you want. I can assume that you want an array in ′hits`...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...