Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...