admin管理员组

文章数量:1415467

I think the question is pretty straightforward, but still:

I have an object obj. How do I create array from this single object? Is it just [obj]

I think the question is pretty straightforward, but still:

I have an object obj. How do I create array from this single object? Is it just [obj]

Share Improve this question asked Sep 8, 2021 at 10:37 newbie codernewbie coder 8381 gold badge12 silver badges30 bronze badges 3
  • 2 That's right. Just put it into array literal and you get an array of single element. – DecPK Commented Sep 8, 2021 at 10:38
  • Yes. There are few other ways too but yours is already the most concise. – Tushar Shahi Commented Sep 8, 2021 at 10:40
  • 1 Just a tip for next time, I wouldn't pose this questions as React Native based, this is purely a JavaScript question. – Dan Zuzevich Commented Sep 8, 2021 at 10:57
Add a ment  | 

2 Answers 2

Reset to default 3

You have several ways to do this:

  1. init an array and push obj inside:

    let array = [];
    array.push(obj);
    
  2. init an array with obj:

    let array = [obj];
    
  3. use fill function:

    let array = new Array(1).fill(obj);
    

You can try this,

const array = [];

array.push(obj);

Output:

array = [obj]

本文标签: javascriptHow do I create array from a single element in react nativeStack Overflow