简体   繁体   中英

Array with values from another array

How can I obtain something like this:

items = [{
  value: 'All',
  checked: false
}, {
  value: 'a',
  checked: false
}, {
  value: 'b',
  checked: false
}, {
  value: 'c',
  checked: false
}];

eg.: console.log(items[2].value)='b'

where 'a', 'b', 'c' .. come from an array arr = ['a', 'b', 'c', 'd', 'e', ...]

I tried with a for

for (var i = 0; i < arr.length; i++) {
    items=[
        {value: 'All', checked: false},
        {value: arr[i], checked: false}
    ]
}

but this is not working and I have no other idea. Is there another way to obtain this? Thank you for your time!

You can use Array.map() :

 const arr = ['all', 'a', 'b', 'c', 'd', 'e']; const result = arr.map(value => ({ value, checked: false })); console.log(result); 

You can try following

var items = [{value: 'All', checked: false}];
for (var i = 0; i < arr.length; i++) {
    items.push({value: arr[i], checked: false})
}

Is this something like this that you seek ?

 const arr = [ 'a', 'b', 'c', 'd', ]; const final = [{ value: 'All', checked: false, }, ...arr.map(x => ({ value: x, checked: false, })), ]; console.log(final); 

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