我想访问一个嵌套的Json文件,并没有弄明白该怎么做:
var createPromise = new Promise(function (resolve, reject) {
ddpclient.call('create_emailConnection',[ddpclient.collections.email], function (err, result) {
console.log([ddpclient.collections.email])
resolve();
if (err) {
logger.error(0, '❌ error user_created')
} else {
logger.debug(5, 'users marked as created')
}
})
})
此回归
email.json
{ HEDGz2aafs2UdSvT3S:
{ _id: 'HEDGz2aafs2UdSvT3S',
batch: '2017-user-created-by-websocket',
creationIP: 'None',
creationDate: 2018-06-14T13:23:58.786Z,
state: [Object],
},
M101KSi360g7cER8D5:
{ _id: 'M101KSi360g7cER8D5',
batch: '2017-box-created-by-websocket',
creationIP: 'None',
creationDate: 2018-06-14T13:24:31.145Z,
state: [Object],
} }
所以我想在我的json文件上获取_id
答案 0 :(得分:0)
因为,对象键HEDGz2aafs2UdSvT3S
,M101KSi360g7cER8D5
看起来是随机且不可预测的,因此您可以在数组对象上使用Object.keys()
并循环遍历它们以获取_id
的值
var arr = [ { HEDGz2aafs2UdSvT3S:
{ _id: 'HEDGz2aafs2UdSvT3S',
batch: '2017-user-created-by-websocket',
creationIP: 'None',
creationDate: '2018-06-14T13:23:58.786Z'
},
M101KSi360g7cER8D5:
{ _id: 'M101KSi360g7cER8D5',
batch: '2017-box-created-by-websocket',
creationIP: 'None',
creationDate: '2018-06-14T13:24:31.145Z'
} } ];
arr.forEach((obj)=>{
keys = Object.keys(obj);
keys.forEach((key)=>{
console.log(obj[key]._id);
});
});
答案 1 :(得分:0)
使用可以使用Array.reduce和Object.keys
您有array
objects
,每个object
有多个objects
,每个_id
都映射到对象的key
_ids
。现在,您可以减少数组以连接所有key
。由于对象的_id
和_id
相同,您可以使用对象的键来提取var arr = [{ HEDGz2aafs2UdSvT3S: { _id: 'HEDGz2aafs2UdSvT3S',batch: '2017-user-created-by-websocket',creationIP: 'None',creationDate: '2018-06-14T13:23:58.786Z'},M101KSi360g7cER8D5:{ _id: 'M101KSi360g7cER8D5',batch: '2017-box-created-by-websocket',creationIP: 'None',creationDate: '2018-06-14T13:24:31.145Z'} } ];
let ids = arr.reduce((a,c) => [...a, ...Object.keys(c)], []);
console.log(ids);
。
let obj = { HEDGz2aafs2UdSvT3S: { _id: 'HEDGz2aafs2UdSvT3S',batch: '2017-user-created-by-websocket',creationIP: 'None',creationDate: '2018-06-14T13:23:58.786Z'},M101KSi360g7cER8D5:{ _id: 'M101KSi360g7cER8D5',batch: '2017-box-created-by-websocket',creationIP: 'None',creationDate: '2018-06-14T13:24:31.145Z'} };
let ids = Object.keys(obj);
console.log(ids);
修改强>
{{1}}
答案 2 :(得分:0)
试试这个:
a.map(x => Object.keys(x).map(y => x[y]._id))
这会返回一个属性数组_id
。
小提琴:{{3}}