我目前正在开发一个项目,我必须使用js和php从网关中检索数据。现在我已经检索了它,但数据没有组织:
{"timestamp":1526524809413,"data":[
{"_id":"rJeixnNtpG","data":"N11B00074","raw":
[78,49,49,66,48,48,48,55,52],"timestamp":1525398515116},
{"_id":"HkzognEYpf","data":"N11E00000","raw":
[78,49,49,69,48,48,48,48,48],"timestamp":1525398515479},
{"_id":"BJxXp4t6M","data":"N11A00029","raw":
[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}
正如您所看到的,有三种类型的数据:一种是以B(N11B00074),E(N11E00000)和A(N11A00029)开头,后面是5位数,这是我想要从字符串中分割出来的数据按类型(B,E和A)分类。
我的网页上有三个表格,并希望根据类型将数据输入到它们中:如B是湿度表,A是温度表,E是pH读数表。
到目前为止,我只是设法将它们列在表格中。
有没有办法可以分离字符串并根据字符串将它们放入数组中?
答案 0 :(得分:0)
您可以使用reduce
对数组中的对象进行分组:
const input={"timestamp":1526524809413,"data":[{"_id":"rJeixnNtpG","data":"N11B00074","raw":[78,49,49,66,48,48,48,55,52],"timestamp":1525398515116},{"_id":"HkzognEYpf","data":"N11E00000","raw":[78,49,49,69,48,48,48,48,48],"timestamp":1525398515479},{"_id":"BJxXp4t6M","data":"N11A00029","raw":[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}]}
const arranged = input.data.reduce((accum, obj) => {
const { data } = obj;
const type = data[3];
const digits = data.slice(5);
if (!accum[type]) accum[type] = [];
accum[type].push({ ...obj, digits });
return accum;
}, {});
console.log(arranged);
// If you want an array and not an object:
console.log(Object.values(arranged));
答案 1 :(得分:0)
如果要将数组分组到对象中。您可以使用reduce
。您可以使用charAt
let arr = {"timestamp":1526524809413,"data":[{"_id":"rJeixnNtpG","data":"N11B00074","raw": [78,49,49,66,48,48,48,55,52],"timestamp":1525398515116}, {"_id":"HkzognEYpf","data":"N11E00000","raw": [78,49,49,69,48,48,48,48,48],"timestamp":1525398515479}, {"_id":"BJxXp4t6M","data":"N11A00029","raw":[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}]};
let result = arr.data.reduce((c, v) => {
let l = v.data.charAt(3); //Get the 4th chatacter
c[l] = c[l] || [];
c[l].push(v);
return c;
}, {});
console.log( result );