按属性拆分对象数组

时间:2018-11-12 17:43:36

标签: javascript arrays object properties

通过属性对对象数组进行分块的最佳方法是什么?

我希望对象的工作方式类似于没有默认值的case语句-在此情况下对象会不断冒泡。

输入

[  
   {  
      "type":"Break"
   },
   {  
      "type":"Not Break"
   },
   {  
      "type":"Break"
   },
   {  
      "type":"Not Break"
   },
   {  
      "type":"Break"
   },
   {  
      "type":"Not Break"
   },
   {  
      "type":"Not Break"
   },
   {  
      "type":"Not Break"
   },
   {  
      "type":"Not Break"
   },
   {  
      "type":"Not Break"
   },
   {  
      "type":"Break"
   }
]

输出

[[{"type":"Break"}, {"type":"Not Break"}], [{"type":"Break"}, {"type":"Not Break"}] ...]

谢谢, 奥利

3 个答案:

答案 0 :(得分:0)

也许尝试Objec.keys

myInputArray.forEach( myInputObject => {
  Object.keys(myInputObject).forEach( key => {
      if(key === 'type'){
          // Do magic
          // get the content by 
          myInputObject[key]
      }
      if(key === 'otherType'){
          // Do more magic
      }
  })
})

亲切的问候

答案 1 :(得分:0)

您可以使用reduce()进行分块,然后在Break上推送一个新的子数组。这是在做一些假设(例如您的第一次输入的类型为Break),因此您需要弄清楚边缘情况,但这应该可以帮助您开始:

let arr = [ { "type":"Break"},{  "type":"Not Break"},{  "type":"Break"},{  "type":"Not Break"},{  "type":"Break"},{  "type":"Not Break"},{  "type":"Not Break"},{  "type":"Not Break"},{  "type":"Not Break"},{  "type":"Not Break"},{  "type":"Break"}]

 let chunks = arr.reduce((arr, item) => {
    if (item.type == 'Break')  arr.push([])  // create a new child
    arr[arr.length-1].push(item)             // push into last child
    return arr
}, [])
console.log(chunks)

答案 2 :(得分:0)

如果我正确理解,则每次初始 type更改时,都需要对输入数据进行分块。如果该假设正确,则可以执行以下操作:

var data = [{ "type": "Break" }, { "type": "Not Break" }, { "type": "Break" }, { "type": "Not Break" }, { "type": "Break" }, { "type": "Not Break" }, { "type": "Not Break" }, { "type": "Not Break" }, { "type": "Not Break" }, { "type": "Not Break" }, { "type": "Break" } ]

const result = data.reduce((r,c) => {
  r.length && c.type != r[r.length-1][0].type ? r[r.length-1].push(c) : r.push([c])
  return r
}, [])

console.log(result)