1

Suppose you have a Javascript object with some properties to display a page with background a text and a title randomly how would you loop inside it to make it display only one item on the object each time?

const list = {
            b1:{
                author: 'Mozart',
                title: 'lacrimosa',
                text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                imageURL: 'url(./assets/img/image.jpg)'
            },
            b2:{
                author: 'Choppin',
                title: 'Waltz in A minor',
                text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                imageURL: 'url(./assets/img/image.jpg)'
            },
            b3:{
                author: 'Bach',
                title: 'Ave Maria',
                text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                imageURL: 'url(./assets/img/image.jpg)'
            },
        }





return(
            <div className="background" style={{background: 'url(./assets/img/image.jpg)'}}>
                <div className="caption">
                    <blockquote>
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
                        <p> artist - <cite>Song</cite></p>
                    </blockquote>
                </div>
            </div>
        )

I tried the Math.random() method but it didn't work

3
  • 1
    Do you want to render random element from list object ? Commented Nov 16, 2018 at 9:27
  • 1
    Have a look at this question that explains how to get a random value from an object. Commented Nov 16, 2018 at 9:27
  • Do you have any code other than an object, like a function that uses Math.random? Commented Nov 16, 2018 at 9:29

6 Answers 6

5

I would better suggest (in order to prevent possible variations of object naming instead of b1, b2, etc.) to use the Object.keys() method:

var listKeys = Object.keys(list);
var randomIndex = Math.floor(Math.random() * listKeys.length);
var randomObject = list[listKeys[randomIndex]];
Sign up to request clarification or add additional context in comments.

Comments

2

The use of Math.random() in David's answer is wrong : you could end up with keys[-1]! The correct way is to use Math.floor(Math.random()*length). Moreover I would use the Object.keys() method to be as general as you need, see this doc. Here is a working solution:

const list = {
  b1: {
    author: 'Mozart',
    title: 'lacrimosa',
    text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    imageURL: 'url(./assets/img/image.jpg)'
  },
  b2: {
    author: 'Chopin',
    title: 'Waltz in A minor',
    text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    imageURL: 'url(./assets/img/image.jpg)'
  },
  b3: {
    author: 'Bach',
    title: 'Ave Maria',
    text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    imageURL: 'url(./assets/img/image.jpg)'
  },
};

const keys = Object.keys(list);
const randomIndex = keys[Math.floor(Math.random() * keys.length)];
const item = list[randomIndex];
console.log(item.author);

The Object.getOwnPropertyNames() method would also work in your specific example.

1 Comment

Worked like a charm! Thank you
0

You can get random item from the object like this

const randomItem = list['b' + Math.floor(Math.random() * 2)]

Comments

0

Either convert the object to Array so you can use Math.random() or create a list of keys, choose one and use it to access the object.

Convert to Array

const arrList = Object.keys(list).map(k => list[k]);
const item = arrList[Math.round(Math.random() * arrList.length - 1)];

Use a list of keys

const keys = ['b1', 'b2', 'b3'];
const item = list[keys[Math.round(Math.random() * keys.length - 1)]];

Comments

0
const randomItem = function (obj) {
  var keys = Object.keys(obj)
  return obj[keys[ keys.length * Math.random() << 0]];
};

1 Comment

Are you able to provide some explanation of what's happening here?
0

You can do this with 3 simple lines of code.

//find the length of your object
const length = Object.keys(list).length

//generate a random number that's between 0 and the length of your object
const random_number = Math.floor((Math.random() * length) + 0);

//get your random item from the object
const random_item = list[Object.keys(list)[random_number]]


console.log(random_item)

Keys can be completely dynamic (b1, b2, b3 can be named as anything - eg: b1, g4, aaa)

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.