foreach对象数组中的联合运算(es6)?

时间:2018-01-10 05:56:06

标签: foreach ecmascript-6 union

我必须使用union操作在对象数组中连接数组。我有一个像下面这样的对象:

let appointments = [{
  Name: "doctor",
  Detail: [Place: "A street", Time: {
    "10:10",
    "15:00",
    "15:30"
  }]
}, {
  Name: "hairdresser",
  Detail: [Place: "B street", Time: {
    "10:10",
    "15:00",
    "15:30"
  }]
}, {
  Name: "hairdresser",
  Detail: [Place: "C street", Time: {
    "10:10",
    "15:00",
    "15:30",
    "14:00"
  }]
}]

我希望使用union在一个数组中的所有细节上连接time属性。 它应该如下所示:我该怎么做?

Time:["10:10","15:00","15:30","14:00"]

2 个答案:

答案 0 :(得分:3)

将所有时间提取到一个新数组,展平它,然后将其设置为删除重复项。



let appointments= [{Name:"doctor", Time:["10:10","15:00","15:30"]},{Name:"hairdresser", Time:["15:00","15:30"]}, {Name:"dentist", Time:["14:00"]}]

const time = [...new Set(appointments
  .map(({Time}) => Time)
  .reduce((all, item) => [...all, ...item]))]

console.log(time)




答案 1 :(得分:0)

<script>
    let appointments= [
    {Name:"doctor", Time:["10:10","15:00","15:30"]},
    {Name:"hairdresser", Time:["15:00","15:30"]},
    {Name:"dentist", Time:["14:00"]}
    ]
    var timeArray=[];
    var lastArray=[]
    appointments.forEach(function(item){
    return timeArray.push(item.Time)
    })
    for (var i = timeArray.length - 1; i >= 0; i--) {
    for (var j = timeArray[i].length - 1; j >= 0; j--) {
    if(lastArray.indexOf(timeArray[i][j])===-1){
        lastArray.push(timeArray[i][j])
    }
    }
    }
    console.log(lastArray)
    </script>

这只是一种方法。