我是一个JS新手试图从一组json地图中提取一些值.地图是这样的:
var tags = [{
Key: 'backup',
Value: 'true'
},
{
Key: 'Name',
Value: 'sdlc-root'
}
]
// Here is my first attempt:
var volName = tags.filter(function(item) {
return item.Key === 'Name';
})
.map(result => {
return result.Value;
});
console.log(volName);Run Code Online (Sandbox Code Playgroud)
结果是: [ 'sdlc-root' ] ,但我只需要String值.
我现在采取的临时解决方案是:
var volName = tags.filter(function(item) { return item.Key === 'Name'; })
.map(result => { return result.Value; })**[0]**;
console.log(volName);
Run Code Online (Sandbox Code Playgroud)
结果是: sdlc-root
我讨厌我的临时解决方案,并希望听到一些改进建议或经验丰富的开发人员的替代方案
您可以找到元素或默认对象并获取所需属性.
var volName = (tags.find(({ Key }) => Key === 'Name') || {}).Value;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |