简体   繁体   中英

conditionally return an object-property in javascript

So this might look like a weird question but bear with me please:

I have a simple array of strings and I want to map it to an array of objects. pretty simple: I would write

arr.map (x => ({
   header  : x,
   sortType: 'basic'
}))

now, here is the question: I would like to check and see if x has a certain value then do not include the sortType at all. I would like to do something like

 arr.map (x => ({
       header  : x,
       x==='test' ? (sortType: 'basic') : //don't provide anything
    }))

so I would like my final array be something like this: And I do not want to have two maps ofcourse!

[
{ header: 'Header One' , sortType: 'basic'},
{ header: 'test' },
{ header: 'Another one' , sortType: 'basic'},
]

You could use two objects with a conditional operator.

arr.map(header => header === 'test'
    ? { header }
    : { header, sortType: 'basic' }
)

Or take Object.assign

arr.map(header => Object.assign({ header }, header !== 'test' && { sortType: 'basic' })) 

Spread short-circuit evaluation result


You may use spreading ( ... ) of expression that conditionally evaluates into necessary sub-object ( {sortType: 'basic'} ):

 const src = ['Header One','test','Another one'], result = src.map (header => ({ header, ...(header!=='test' && {sortType: 'basic'}) })) console.log(result)
 .as-console-wrapper{min-height:100%;}

 var arr = ['test','love','javascript'];

 const output = arr.map (x => {
       const obj = {
           header  : x
       };
       if(x === "test") obj.sortType = "basic";
       return obj;
});

console.log(output);
// [{header: "test", sortType: "basic"}, {header: "love"}, {header: "javascript"}]

I know you got quite some nice answers already, in case you prefer this approach.

const arr = ['penguinsinpijamas', 'test'];

var mappy = arr.map(x => {
    let obj = {'header': x};
    if (obj.header === 'test') obj.sortType = 'basic';
    return obj})

mappy.forEach(m => console.log(m))

Returns:

Object {header: "penguinsinpijamas"}
Object {header: "test", sortType: "basic"}

Try this

 var arr = ['test','love','javascript']; var result = arr.map (x => ({ header : x, sortType: x==='test'?undefined:'basic' })) console.log(JSON.stringify(arr)); console.log(JSON.stringify(result));

output :

["test","love","javascript"]
[{"header":"test"},{"header":"love","sortType":"basic"},{"header":"javascript","sortType":"basic"}]

you should apply logic for the value.

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