简体   繁体   中英

Need elegant way to extract value as String from json maps in Javascript

I am a JS newbie trying to extract some value from an array of json maps. The map is something like:

 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); 

The result is: [ 'sdlc-root' ] , but I only need the String value.

The temporary solution I take for now is:

var volName = tags.filter(function(item) { return item.Key === 'Name'; })
                  .map(result => { return result.Value; })**[0]**;
console.log(volName);    

The result is: sdlc-root

I hate my temporary solution, and would like to hear some advice for improvement or alternatives from experienced developers

您可以找到该元素或默认对象,并获取想要的属性。

var volName = (tags.find(({ Key }) => Key === 'Name') || {}).Value;

Write a custom function like below

 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM