这是我的结构
[{
"date": "2019-01-10T18:30:00.000Z",
"time": "2019-01-11T04:37:49.587Z",
"abc_Info": {
"_id": "5c381da651f18d5040611eb2",
"abc": 2.5,
"guardian": "XYZ"
}
}]
我想要的是
[{
"date": "2019-01-10T18:30:00.000Z",
"time": "2019-01-11T04:37:49.587Z",
"abc": 2.5,
"guardian": "XYZ"
}]
代码
this._model.find(params, (err, docs) => {
if (err) {
var response = this.errorResponse("error", 500, null);
res.send(response);
} else {
for (var i = 0; i < docs.length; i++) {
const abc= {
"date": docs[i].date,
"time": docs[i].time,
"abc_Info":docs[i].abc_Info //this is object, i couldn't select value separately from this object
}
if (docs[i].abc_Info != undefined) {
abcArray.push(abc);
}
}
res.send(abc);
}
});
我正在尝试从“ abc_Info”:docs [i] .abc_Info.abc 之类的对象中选择值,但是我无法做到这一点,它的抛出错误。 我可以通过两种方式实现这一目标。
答案 0 :(得分:1)
选择这个。
const abc= {
"date": docs[i].date,
"time": docs[i].time,
"abc":docs[i].abc_Info.abc,
"guardian":docs[i].abc_Info.guardian
}
答案 1 :(得分:1)
希望这会有所帮助
var d=[{
"date": "2019-01-10T18:30:00.000Z",
"time": "2019-01-11T04:37:49.587Z",
"abc_Info": {
"_id": "5c381da651f18d5040611eb2",
"abc": 2.5,
"guardian": "XYZ"
}
}]
d[0]=Object.assign(d[0],d[0].abc_Info);
delete d[0]['abc_Info'];
delete d[0]['_id'];
console.log(d);
答案 2 :(得分:1)
let x = {
"date": "2019-01-10T18:30:00.000Z",
"time": "2019-01-11T04:37:49.587Z",
}
let abc_Info = {
"_id": "5c381da651f18d5040611eb2",
"abc": 2.5,
"guardian": "XYZ"
}
// to concat
let z = {...x, ...abc_Info}
console.log(z)
您可以将以上ES6 spread operator
用作原因
Object.assign
的性能要好得多,因此如下所示:
或let z = Object.assign(x, abc_info);
在您的代码中应该是这样的:
const abc= {...{
"date": docs[i].date,
"time": docs[i].time,
}, ...docs[i].abc_Info}
答案 3 :(得分:0)
使用Spread运算符,而不是使用for循环和推送,请使用Array.prototype.map
let docs= [{
"date": "2019-01-10T18:30:00.000Z",
"time": "2019-01-11T04:37:49.587Z",
"abc_Info": {
"_id": "5c381da651f18d5040611eb2",
"abc": 2.5,
"guardian": "XYZ"
}
}]
let abcArray = docs.map(({date, time, abc_Info}) => {
delete abc_Info._id;
return {date, time, ...abc_Info }
});
console.log(abcArray)
答案 4 :(得分:-1)
对不起,这是我的错误。我应该在if语句中声明对象。现在可以正常工作
if (docs[i].abc_Info != undefined) {
const abc= {
"date": docs[i].date,
"time": docs[i].time,
"abc_Info":docs[i].abc_Info
}
abcArray.push(abc);
}