我正在尝试按项属性对项目数组进行分组,然后从0
开始重新索引结果。
以下函数返回一组分组的项目。
groupItemBy(array, property) {
let hash = {},
props = property.split('.');
for (let i = 0; i < array.length; i++) {
let key = props.reduce( (acc, prop) => {
return acc && acc[prop];
}, array[i]);
if (!hash[key]) hash[key] = [];
hash[key].push(array[i]);
}
return hash;
}
结果是一个数组数组,类似于:
[{
"1193312":[
{
"description":"Item 1",
"number": "1193312"
}
],
"1193314":[
{
"itemDesc":"Item 2"},
"number": "1193314"
{
"description":"Item 3",
"number": "1193314"
}
],
etc...
}]
从这里开始,我想将1193312
映射到0
,将1193314
映射到1
等。
我在结果上尝试.filter(val => val)
,但这似乎没有效果。
答案 0 :(得分:2)
您需要使用中间密钥替换:
function groupItemBy(array, property) {
let hash = {}
let props = property.split('.')
let keys = []
for (let i = 0; i < array.length; i++) {
let key = props.reduce((acc, prop) => {
return acc && acc[prop];
}, array[i]);
let subst = keys.indexOf(key)
if (subst === -1) {
keys.push(key)
subst = keys.length - 1
}
if (!hash[subst]) hash[subst] = [];
hash[subst].push(array[i]);
}
return hash;
}
答案 1 :(得分:2)
您可以将map
用于数组部分,将Object.values
和reduce用于重新编号部分。
const data = [{
"1193312":[
{
"time":"2018-02-20",
"description":"Item 1",
"number": "1193312"
}
],
"1193314":[
{
"time":"2018-02-21",
"itemDesc":"Item 2",
"number": "1193314"
},{
"time":"2018-02-21",
"description":"Item 3",
"number": "1193314"
}
]
}];
const renumbered =
data.map((m) => Object.values(m).reduce((a,v,ix) => (a[ix] = v, a), {}));
console.log(renumbered);
答案 2 :(得分:1)
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.PNG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: isCamera ? this.camera.PictureSourceType.CAMERA : this.camera.PictureSourceType.PHOTOLIBRARY,
correctOrientation: true,
}
答案 3 :(得分:0)
如果您可以使用var output = {
suba: inputArray[n].integervalue,
subb: inputArray[n].integervalue;
subc: inputArray[n].integervalue;
subd: inputArray[n].booleanvalue;
sube: inputArray[n].booleanvalue;
sudf: inputArray[n].booleanvalue;
}
:
#include <stdio.h>
int main(void)
{
int state;
for(state=0; ; ) {
int ch;
ch = getc(stdin);
if (ch == EOF) break;
switch (state) {
case 0: /* initial */
if (ch == '.') { state = 1; continue; }
break;
case 1:
if (ch == '\n') { state = 0; break; }
continue;
}
putc(ch, stdout);
}
return 0;
}
&#13;