Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

Map object inside array in javascript?

This is my array:

const array = [
    {
        "fare": "399.00",
        "passenger": {
            "age": "21",
            "gender": "MALE",
            "name": "Test1"
        },
    },
    {
        "fare": "399.00",
        "passenger": {
            "age": "21",
            "gender": "FEMALE",
            "name": "Test2"
        },
    }
]

How to map the object inside the array, and how to convert the object to the required output

Required output:

Test1(M), Test2(F)

Above contains "name" and gender - if its male then just "M" and if its female just "F"

As of now i tried,

array.map(o => ({ name: o.passenger.name, gender: o.passenger.gender })))

But how to convert this as expected output !

question from:https://stackoverflow.com/questions/65880983/map-object-inside-array-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like this

const array = [{ "fare": "399.00", "passenger": { "age": "21", "gender": "MALE", "name": "Test1" }, }, { "fare": "399.00", "passenger": { "age": "21", "gender": "FEMALE", "name": "Test2" }, } ];

const output = array
  .map(({passenger}) => `${passenger.name}(${passenger.gender.slice(0,1)})`)
  .join(", ")

console.log(output); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...