Home > database >  Javascript - How can I build a sentence to display data based on whether data values are > 0?
Javascript - How can I build a sentence to display data based on whether data values are > 0?

Time:06-03

I am getting back data from an API - just an object with numerical values pertaining to each key - and then building a simple sentence to display the data for the user. However, I only want to include a value from the data if it is bigger than 0. Here is an example with mock data:

let data = {red: 100, blue: 200, yellow: 0, green: 400};

let resultsSentence = `We found ${data.red} red posts, ${data.blue} blue posts, and ${data.green} green posts.`

console.log(resultsSentence)

As you can see, I left yellow out from the results sentence because it has a value of 0. Of course, I need to be able to generate this sentence dynamically based on whatever data is returned. If I use conditionals, it will be a mess, since there are too many possible scenarios (writing 15 if/else statements does not seem like a good approach).

How can I handle this? I need to generate the sentence based on whichever values are > 0. At first I thought, easy, I'll just push all the values into an array, check for 0's, and remove any items that are equal to 0 from the array. Then, build the sentence based on however long the array is, i.e., if the array length is 3, then refer to each value as array[0], array[1], array[2]. However, this presents a problem, since I need to be able to clarify which values are which in the sentence. For example, if I remove yellow from the array, the array length will be 3, but I won't know which value was removed.

Can anyone help me come up with an efficient solution for this?

CodePudding user response:

You can use a simple for..of loop to iterate over the object's keys and values, building up your string inside of it.

This does result in an oxford comma but you can strip that in the conditional (where you choose to use and instead).

let data = {red: 100, blue: 200, yellow: 0, green: 400};
let res = 'We found '

// Keep a record of how many keys we've processed so we know when we're at the end
let i = 1
for (const [k, v] of Object.entries(data)) {
  // we could just continue early here, but we want to keep adding to `i`
  if (v > 0) { 
    // This is the last key so use `and` not a comma
    if (i === Object.keys(data).length) {
      res  = `and ${v} ${k} posts.`
    } else {
      res  = `${v} ${k} posts, `
    }
  }
  i  
}

console.log(res)

CodePudding user response:

Try this

let data = {red: 100, blue: 200, yellow: 0, green: 400};

let str = [];
let len = Object.keys(data).length;
Object.entries(data).forEach(([key, val], index) => {
    let isLast = (len - 1 == index) && str.length > 0;
    if(val > 0) str.push((isLast ? 'and ' : '')   `${val} ${key} posts`);
})

let resultsSentence = 'We found '   str.join(', ')
console.log(resultsSentence)

CodePudding user response:

try this (without depedencies)

const keys = Object.keys(data)
const values = Object.values(data)
let string = 'we found'

values.map((item, index)=>{
  if(item > 0){
        string  = ` ${item} ${keys[index]} posts,`
  }
})
console.log(string.slice(0,-1) '.')

try with lodash as

const _ = require('lodash')

let data = {red: 100, blue: 200, yellow: 0, green: 400};
let string = 'we found'

_.map(data,(value,key)=>{
  if(value > 0){
    string  = ` ${value} ${key} posts,`
  }
})
console.log(string.slice(0,-1) '.')

CodePudding user response:

Could be you have an outdated browser.

I tested your code on Chrome Version 102.0.5005.63 (Official Build) (64-bit)

let data = {red: 100, blue: 200, yellow: 0, green: 400};

let resultsSentence = `We found ${data.red} red posts, ${data.blue} blue posts, and ${data.green} green posts.`

console.log(resultsSentence);

And got this result:

We found 100 red posts, 200 blue posts, and 400 green posts.

So unless I don't understand your question, there are no errors when we include the object of data to access its properties.

Let me know.

  • Related