0

I have an array formed by a series of objs, I would like to make sure to assign an object to a variable. If the object doesn't exist I would like to assign {} (empty obj).

Can you give me some advice?

let a = [
{
  username: 'james.bond',
  name: 'James Bond',
  email: '[email protected]',
},
{
  username: 'sherlock.holmes',
  name: 'Sherlock Holmes',
  email: '[email protected]',
},
{
  name: 'Shinichi Kudo',
  email: '[email protected]',
  badgeText: '21',
  badgeColor: '#fff',
  badgeBackground: '#25dbd2',
  joined: 'Joined at Jun 31, 2021',
  circle: ['transparent', 'transparent'],
},
{
  name: 'Arthur Conan Doyle',
  email: '[email protected]',
  circle: ['transparent', 'transparent'],
},
  ];
        
   const [b = {}, c = [] ] = a;

console.log(b, c);//b=a[0], c=[a[1],a[2],a[3]]

1
  • 1
    What? Please add an expected output to your question, it is currently not possible to understand your desired result. Commented Jun 9, 2020 at 10:09

2 Answers 2

2

Try this:

const [ b = {}, c = {}, d = {} ] = a;

Or:

const [ b = {}, ...c] = a;

c will be an array contains the rest of a except the first element.

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

2 Comments

Thank you for replying I changed the question slightly, can you help me?
@Paul this might help: const [ b = {}, ...c] = a
0

try this:

let a = [{
    username: 'james.bond',
    name: 'James Bond',
    email: '[email protected]',
  },
  {
    username: 'sherlock.holmes',
    name: 'Sherlock Holmes',
    email: '[email protected]',
  }
];

const [b = {}, c = {}, d = {} ] = a;//a.map(x => x)

console.log(b, c, d);

1 Comment

Thank you for replying I changed the question slightly, can you help me?

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.