-1

I have an object with multiple keys and each key has an array as a value. how do I iterate through the array and log only 1 value for each key? I have the object set up as such:

const obj = { 'keyA': ['value 1', 'value 2'], 'keyB': ['value 3', 'value 4'] } 

I need it to return the chosen key and any of the values in the array.

after trying several suggestions, was still not getting the results I was looking for. So, I tried from a different angle.

enter code here let noun = ['I', 'We', 'You']; let adverbA = ['will be', 'can be', 'are']; //For We and You let adverbB = ['will be', 'can be', 'am']; //For I let verb = ['special', 'important', 'powerful', 'loved', 'beautiful', 'amazing']; const userChoice = noun => { for (let i = 0; i > noun.length; i++) { for (let j = 0; j > adverbA.length; j++); for (let k = 0; k > adverbB.length; k++); for (let m = 0; m > verb.length; m++) if (i === [0]){ console.log (`${this.noun} ${[k]} more ${[m]} than ${this.noun} know!`); } else if (i === [1] || [2]) { console.log (`${this.noun} ${[j]} more ${[m]} than ${this.noun} know!`); } else { console.log ('Invalid Entry') } } } console.log (userChoice('I')); 

It Seems like it should work, but I keep getting 'undefined' returned. Am I missing something somewhere?

2
  • you are given 1 key and you have to return just 1 value from the array on the given key correct? why do you need to return just 1 value? any value at random? Commented Apr 5, 2023 at 14:24
  • Object.keys(obj).forEach(key => console.log(key, obj[key].length ? obj[key][0] : "No Value found!" )) --- Try this, it also checks if the array is empty for no Key Commented Apr 5, 2023 at 14:29

3 Answers 3

0

const obj = { 'keyA': ['value 1', 'value 2'], 'keyB': ['value 3', 'value 4'] } Object.keys(obj).forEach((key) => { console.log(key, '=', obj[key][0]) // logging one value, the first one in the array })

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

Comments

0

I don't know what you wan't to do with your object, but here's how you'll log the first value of each of your arrays.

Object.keys(obj).forEach(function(k){ console.log(obj[k][0]); }); 

EDIT after OP comment

then to log a random an array :

console.log(obj[k][Math.floor(Math.random() * k.length)]); 

1 Comment

What I'm really trying for is to log a random value from the array when a specific key is chosen
0

Try this : It checks if the value array is empty and also sends a random value if not

const obj = { 'keyA': ['value 1', 'value 2', 'value 3', 'value 4'], 'keyB': ['value 5', 'value 6', 'value 7'], 'keyC': [], } Object.keys(obj).forEach(key => console.log(key, obj[key].length ? obj[key][Math.floor((Math.random() * (obj[key].length)))] : "No Value found!" ))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.