skip to Main Content

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?

3

Answers


  1. 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)]);
    
    Login or Signup to reply.
  2. 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
    })
    Login or Signup to reply.
  3. 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!" ))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search