遍历对象以获取存储的数组值

时间:2020-11-10 21:29:45

标签: typescript mongoose

对于我正在处理的项目,我正在传递数据以加载保存的数据。当我得到数据时,它像这样通过:

{response: 6, plan: {…}}
plan:
items: Array(9)
0: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418e8", id: 0, unitId: 10810, …}
1: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418e9", id: 1, unitId: 10810, …}
2: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418ea", id: 2, unitId: 8874, …}
3: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418eb", id: 3, unitId: 3762, …}
4: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418ec", id: 4, unitId: 3568, …}
5: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418ed", id: 5, unitId: 11000, …}
6: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418ee", id: 6, unitId: 4240, …}
7: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418ef", id: 7, unitId: 11000, …}
8: {position: {…}, dimensions: {…}, _id: "5fa95e22d33ebceedf3418f0", id: 8, unitId: 4240, …}
length: 9
__proto__: Array(0)
room:
depth: 3000
height: 2500
name: "Plan"
width: 3000
__proto__: Object
__v: 0
_id: "5fa95e22d33ebceedf3418e7"
__proto__: Object
response: 6

响应:6就是手动设置的值,以表明数据检索成功。

数据通过对象数据进入。现在,我的下一个任务是遍历数据并获取数组项中的项。最好的方法是什么?

我认为可能是这样的:

for (i in data) {
console.log(i)
}

仅作为示例,但是仅输出“计划”。我在哪里出错,如何检索数组?

谢谢

2 个答案:

答案 0 :(得分:1)

你不只是从字面上做

data.plan.items

或者仅输出计划

data.items

答案 1 :(得分:0)

您可以将lodash库与pick一起使用 像这样:

_.pick(object, ['items']);

请参阅https://lodash.com/docs#pick