How does js deal with wanting to get the data structure?
example 1 var arr = [
]
{
date: "2018-11-27",
time: "1:002:00",
},
{
date: "2018-11-27",
time: "3:004:00"
},
{
date: "2018-01-10",
time: "5:00"
}
];
hope to get [{date: "2018-11-27", time: "1:00, 2:00, 3:00, 4:00"}, {date: "2017-01-10", time: "5:00"}]
example 2
var arr1 = [{id: 1,name: ""}, {id: 2,name: ""}];
var arr2 = [{id: 1,age: 10}, {id: 2, age: 20}];
[{id: 1, name: "", age: 10}, {id: 2,name: "", age: 20}]
it is best to provide a variety of solutions!
how does js deal with the desired data structure?
js
cannot handle data structures that you want
, you can only process data structures according to specific rules
.
example 1
"1:00, 2:00, 3:00, 4:00"
is an attribute string of the same name through ,
, while the result of an attribute of the same name in the example 2
is directly 'Xiaoming'
, so what kind of specific rule
do you actually want?
< H2 > add < / H2 >
example 1
var arr = [{
date: "2018-11-27",
time: "1:002:00",
},
{
date: "2018-11-27",
time: "3:004:00"
},
{
date: "2018-01-10",
time: "5:00"
}
];
arr.reduce((res, acc) => {
let i = res.findIndex(d => d.date === acc.date);
if (i > -1) {
res[i].time = [res[i].time, acc.time].join('')
} else {
res.push(acc)
}
return res;
}, [])
example 2
let arr1 = [{ id: 1, name: '' }, { id: 2, name: '' }];
let arr2 = [{ id: 1, age: 10 }, { id: 2, age: 20 }];
function merge(arr1, arr2, key) {
return arr1.map(d1 => {
let same = arr2.find(d2 => d2[key] === d1[key]);
return same ? Object.assign({}, d1, same) : d1
})
}
merge(arr1, arr2, 'id')//[ { id: 1, name: '', age: 10 },{ id: 2, name: '', age: 20 } ]
what do I do?
deal with example 1 loop step by step according to the rules you provide. If the date is the same, merge
the first example is just thinking. You need to practice it yourself.
var arr = [{
date: "2018-11-27",
time: "1:002:00",
},
{
date: "2018-11-27",
time: "3:004:00"
},
{
date: "2018-01-10",
time: "5:00"
}
];
arr.map((e,i)=>{
if(i < arr.length - 1 && e["date"] == arr[i+1]["date"]){
arr[i+1]["time"] = e["time"] + "" +arr[i+1]["time"] ;
arr.splice(i,1);
}
})