0

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!

1
  • What does "not working" mean? You're adding the All property in each loop iteration. Commented Oct 25, 2018 at 14:48

3 Answers 3

4

You can use Array.map():

const arr = ['all', 'a', 'b', 'c', 'd', 'e'];

const result = arr.map(value => ({ value, checked: false }));

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Very effective.
2

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})
}

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.