[英]How to extract in elegant way the string using the regular expression in JavaScript?
[英]Need elegant way to extract value as String from json maps in Javascript
我是一個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);
結果是: [ 'sdlc-root' ]
,但是我只需要String值。
我現在采取的臨時解決方案是:
var volName = tags.filter(function(item) { return item.Key === 'Name'; })
.map(result => { return result.Value; })**[0]**;
console.log(volName);
結果是: sdlc-root
我討厭我的臨時解決方案,並且想聽聽經驗豐富的開發人員的一些改進建議或替代方案
您可以找到該元素或默認對象,並獲取想要的屬性。
var volName = (tags.find(({ Key }) => Key === 'Name') || {}).Value;
編寫如下的自定義函數
var tags = [{ Key: 'backup', Value: 'true' }, { Key: 'Name', Value: 'sdlc-root' } ] function f(tags) { for (i = 0; i <= tags.length; i++) { if (tags[i] && tags[i]['Key'] === 'Name') { return tags[i]['Value'] } } } console.log(f(tags))
const tagsObj = tags.reduce((a, c) => { a[c.Key] = c.Value; return a }, {})
// {backup: "true", Name: "sdlc-root"}
console.log(tagsObj["Name"])
// "sdlc-root"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.