我有一个如下所示的数组
[
{"st":"10:30,22:30","day":1},
{"st":"9:30,20:30","day":3},
{"st":"9:30,20:30","day":4},
{"st":"11:0,23:30","day":7},
{"st":"11:0,23:30","day":6},
{"st":"8:0,23:0","day":2},
{"st":"8:0,23:0","day":5}
]
我想像下面这样转换它
[
{"st":"10:30,22:30","day":[1]},
{"st":"9:30,20:30","day":[3,4]},
{"st":"11:0,23:30","day":[7,6]},
{"st":"8:0,23:0","day":[2,5]}
]
根据重复的“st”值,我想合并那些相应的日期。 我尝试了很多方法但我无法做到。有人可以帮我吗?提前致谢。
最佳答案
一种方法如下:
var yourArray = [
{"st":"10:30,22:30","day":1},
{"st":"9:30,20:30","day":3},
{"st":"9:30,20:30","day":4},
{"st":"11:0,23:30","day":7},
{"st":"11:0,23:30","day":6},
{"st":"8:0,23:0","day":2},
{"st":"8:0,23:0","day":5}
];
var newArray =
Array.from(new Set(yourArray.map(elem => elem.st))) // get unique st's
.map(elem => ({
st: elem,
day: yourArray.filter(el => el.st === elem).map(el => el.day) // get array of days
}));
console.log(newArray);
请注意,这使用了 ES6 功能,您需要使用转译器(例如 Babel)才能在不兼容 ES6 的浏览器中使用它。
资源
关于javascript - 将重复项合并到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38197827/