简体   繁体   中英

Push item onto array on condition in one line

I want something like this and I would like to know if this is possible in JavaScript in one line, or I have to write an if statement

// these versions adds fasle to the array if condition = false let arr = await getArray(params).push(condition && itemToAdd); arr = await getArray(params).push((() => condition && itemToAdd)()); // this version adds undefined to the array if condition = false arr = await getArray(params).push((() => { if (condition) return itemToAdd })());

(the reason I included the getArray part is cuz that's how it looks in my code and I don't actually save this array to a var arr only its being returned right away to its calling function, so that's why I don't want to add a line for the if statement...)

Not sure why you want to do it in a single line, but this can work

let arr = [...await getArray(), itemToAdd].slice(0, condition? undefined: -1);

Here we are pushing the itemToAdd in the array regardless of the condition, but we remove the last element ( itemToAdd ) if the condition is false.

if you are working with reactjs then you can use useState for conditions

const [isCondition, setisCondition] = useState(false);

//but you need if/else to change useState

 if(this_happens) {

setisCondition(true) } else { setisCondition(false) }

//you can do it as like

let arr = await getArray(params).push(isCondition && itemToAdd);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM