简体   繁体   English

如何在需要时将整个 object 转换为数组?

[英]How to convert whole object into Array when needed?

Since long time am getting problem in this object to array and array to object.由于长期以来在此 object 到阵列和阵列到 object 中遇到问题。 As i am working on external api - every codes are totally depend on the output from API因为我正在处理外部 api - 每个代码都完全取决于 API 中的 output

So here is my problem - Sometime am getting object (as there would be only single element in the result ) and sometime am getting a array with more than 2 or 3 items inside it, so when ever i perform some action like removing or manipulating or adding to single object am getting error on array and vise versa !所以这是我的问题 - 有时我得到 object (因为结果中只有一个元素),有时我得到一个包含超过 2 或 3 个项目的数组,所以当我执行一些操作时,比如删除或操作或添加到单个 object 在阵列上出现错误,反之亦然!

Whats the solution for this:(这是什么解决方案:(

Today i faced a problem:今天我遇到了一个问题:

Here is my object & Array:这是我的 object 和阵列:


//-------------Object--------------//
        "inventoryItems": {
            "age": "26",
            "gender": "MALE",
            "title": "Mr",
            "user" : "John"
        },

This is how i get from api when there is only one user presented,当只有一个用户出现时,这就是我从 api 获得的方式,

//---------------Array-------------//

"inventoryItems": [
        {
            "age": "26",
            "gender": "MALE",
            "title": "Mr",
            "user" : "John"
         },
         {
            "age": "26",
            "gender": "MALE",
            "title": "Mr",
            "user" : "John"
         }
   ]

So, based on Array - i have created a map to miniplate the data but when it gets single object it throws error !因此,基于 Array - 我创建了一个 map 来微型化数据,但是当它获得单个 object 时,它会引发错误!

So, far:至今:

I tried to add [] on object and it works - but when it comes to array it throws error as it will become nested array我试图在 object 上添加 [] 并且它可以工作 - 但是当涉及到数组时它会抛出错误,因为它将成为嵌套数组

Is there any industry practice for this problem?有没有针对这个问题的行业惯例? Am sure developers would have found a great solution for this already !相信开发人员已经为此找到了一个很好的解决方案!

I think the best thing will be to make sure that your api provide an array in both cases so that when there is only on item your code will do the same action without crashing.我认为最好的办法是确保您的 api 在这两种情况下都提供一个数组,这样当只有项目时,您的代码将执行相同的操作而不会崩溃。

Though you can use a condition like this:虽然您可以使用这样的条件:

if (inventoryItems.length != undefined) {
  // This is an array
} else {
  // This is an object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM