0
var userLists = {
    user0 : {username: 'user9110252username', genrePref: 'user9110252genre'},
    user1 : {username: 'Jon', genrePref: 'rock'},
    user2 : {username: 'Lucy', genrePref: 'pop'},
    user3 : {username: 'Mike', genrePref: 'rock'},
}

I am getting input like userLists.user from somewhere it should be like userLists.user0 how can i convert this request

var i =0;
for(var key in userLists) {
   console.log(userLists.user+i)
   i++;
}
5
  • 2
    Just use console.log(userLists[key]). You don't need another i variable. Also, consider using a users array instead of using consecutive numeral keys Commented May 15, 2020 at 4:59
  • Is it possible to use foreach for iteration of javascript ?? Commented May 15, 2020 at 5:53
  • Please add the code Commented May 15, 2020 at 5:54
  • var i = 0; userLists.forEach((key, value) => { console.log(key); i++ }) is this possible in object iteration ? Commented May 15, 2020 at 6:13
  • @SunilDubey for (const [key, value] of Object.entries(userLists)) { console.log(key); } Commented May 15, 2020 at 9:27

2 Answers 2

1

If you want to use forEach or map you can do that on arrays but since you have an object you can use Object.entries for getting an array of arrays. There are also Object.keys and Object.values.

var userLists = {
    user0 : {username: 'user9110252username', genrePref: 'user9110252genre'},
    user1 : {username: 'Jon', genrePref: 'rock'},
    user2 : {username: 'Lucy', genrePref: 'pop'},
    user3 : {username: 'Mike', genrePref: 'rock'},
}

Object.entries(userLists).forEach(([key, value]) => {
  console.log(key, value);
})

Sign up to request clarification or add additional context in comments.

1 Comment

hmm but Is there any way to fix this code ? var i =0; for(var key in userLists) { console.log(userLists.user+i) i++; }
1

If I understand your question correctly, do you want like this ?

var userLists = {
    user0 : {username: 'user9110252username', genrePref: 'user9110252genre'},
    user1 : {username: 'Jon', genrePref: 'rock'},
    user2 : {username: 'Lucy', genrePref: 'pop'},
    user3 : {username: 'Mike', genrePref: 'rock'},
}

var result = Object.fromEntries(Object.entries(userLists).map(([k,v], i)=>[k=i, v]));

console.log(result);

Or you can do similar manipulation inside map function according to your requirement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.