简体   繁体   English

如何使用javascript将object of object个数组对象改成数组对象

[英]How to change object of object of array objects to array objects using javascript

I would like to know how to flatten the array of objects without flap map in javascript我想知道如何在 javascript 中不带 flap map 的情况下展平对象数组

If the of object of arrays object has length greater than 1, flatten如果 arrays 的 object object 的长度大于1,展平

in my example property black has more than object so return that in array of objects在我的示例中, property black超过 object,因此在对象数组中返回它

var obj ={
    "details": {
        "black": [
            {
            value: 100,
            name: "xxx"
            },
            {
            value: 200,
            name: "yyy"
            }
        ]
    },
    "sales": {
        "blue": [
            {
               value: 50,
               name: "abc"
            }
        ],
        "ALL": [
            {
              value: 20,
              name: "100"
            }
        ]
    }
}

Expected Output预计 Output

[
  {
    value: 100,
    name: "xxx"
  },
  {
    value: 200,
    name: "yyy"
  }
]

have tried试过

const result = Object
    .values(obj)
    .flatMap(v => 
        Object.values(v as any)
            .filter((group: any) => group.length > 1)
    )

without flapmap how to do using javascript没有 flapmap 如何使用 javascript

You can create a recursive flatten function using Array.reduce() that takes a multidimensional array, and converts it to a flat array (TS playground):您可以使用Array.reduce()创建一个递归flatten function ,它采用多维数组,并将其转换为平面数组(TS playground):

 const obj = {"details":{"black":[{"value":100,"name":"xxx"},{"value":200,"name":"yyy"}]},"sales":{"blue":[{"value":50,"name":"abc"}],"ALL":[{"value":20,"name":"100"}]}} const flatten = arr => arr.reduce((acc, a) => acc.concat( Array.isArray(a)? flatten(a): a ), []) const result = flatten(Object.values(obj).map(v => Object.values(v).filter(group => group.length > 1) ) ) console.log(result)

Note : you can also use Array.flat() but since it came out with Array.flatMap() you would probably still have a compatibility problem.注意:您也可以使用Array.flat()但由于它与Array.flatMap()一起出现,您可能仍然会遇到兼容性问题。

 var obj ={ "details": { "black": [ { value: 100, name: "xxx" }, { value: 200, name: "yyy" } ] }, "sales": { "blue": [ { value: 50, name: "abc" } ], "ALL": [ { value: 20, name: "100" } ] } } console.log(obj.details.black)

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

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