const msg1 = {
fname: 'Divyesh',
lname: 'Patel',
}
const person = {
fullname: function (city, num) {
return this.fname + " " + this.lname + " " + city + " " + num;
}
}
console.log(person.fullname.call(msg1, "Surat", "972737"));
Вы можете использовать простой reduce
, чтобы получить это:
const input=[{index:0,value:3},{index:0,value:3},{index:0,value:3},{index:1,value:3},{index:1,value:3},{index:2,value:3},{index:2,value:3}]
/* If index exists in the accumulator object, use that.
else, create the index and point to an empty array
push the item in context to the array
*/
const output = input.reduce((acc, v) => {
acc[v.index] = acc[v.index] || [];
acc[v.index].push(v);
return acc;
}, {});
console.log(output)
Вот короткая версия:
const input=[{index:0,value:3},{index:0,value:3},{index:0,value:3},{index:1,value:3},{index:1,value:3},{index:2,value:3},{index:2,value:3}]
const output = input.reduce((a,v) => ((a[v.index] = a[v.index] || []).push(v), a), {});
console.log(output)
Выполните простую операцию reduce
:
const data = [{
index: 0,
value: 3
},
{
index: 0,
value: 3
},
{
index: 0,
value: 3
},
{
index: 1,
value: 3
},
{
index: 1,
value: 3
},
{
index: 2,
value: 3
}, {
index: 2,
value: 3
}
];
const modified = data.reduce((val, acc) => {
if (acc[val.index]) {
acc[val.index].push(val);
} else {
acc[val.index] = [{
index: [val.index],
value: [val.value]
}];
}
return acc;
}, {});
console.log(modified);
Вы можете использовать простой цикл for
const input = [
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 1, value: 3},
{index: 1, value: 3},
{index: 2, value: 3},
{index: 2, value: 3}
];
const newArray = {}
for(var i of input) {
if(newArray[i.index]) {
newArray[i.index].push(i)
} else {
newArray[i.index] = [i]
}
}
console.log(newArray)
Здесь у вас есть одна версия, использующая Reduce () и Object.assign () :
const input = [
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 1, value: 3},
{index: 1, value: 3},
{index: 2, value: 3},
{index: 2, value: 3},
{index: 0, value: 3}
];
let obj = input.reduce((res, curr) =>
{
if (res[[curr.index]])
res[[curr.index]].push(curr);
else
res = Object.assign({[curr.index]: [curr]}, res);
return res;
}, {});
console.log(obj);
В предыдущем примере будут созданы группы всех объектов с одинаковым свойством index
. Однако, если вы хотите разделить объекты полосами, которые имеют равные indexes
, вы можете сделать это:
const input = [
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 1, value: 3},
{index: 1, value: 3},
{index: 2, value: 3},
{index: 2, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 0, value: 3},
{index: 2, value: 3},
{index: 2, value: 3}
];
let obj = input.reduce((res, curr) =>
{
if (curr.index === res.last)
res.r[res.idx - 1].push(curr);
else
{
res.r = Object.assign({[res.idx]: [curr]}, res.r);
res.last = curr.index;
res.idx = res.idx + 1;
}
return res;
}, {r: {}, idx: 0, last: null});
console.log(obj.r);