简体   繁体   中英

javascript function to get list of objects and return new key with new value in new array

for privacy I explain simple example. function that get personal list and return new key with new value like below:

personalList = [{
        firstName: "elena",
        lastName: "zakharova"
    },
    {
        firstName: "alex",
        lastName: "farmanda"
    },
    {
        firstName: "mike",
        lastName: "kenan"
    }]

output should be like this:

desiredList =[{fullname :'elena zakhrova'},{fullname :'alex farmanda'}, fullname : 'mike kenan']

tried some ways but unfortunately did not get answer

Any solutions would be appreciated.

You can use map

 const personalList = [{ firstName: "elena", lastName: "zakharova" }, { firstName: "alex", lastName: "farmanda" }, { firstName: "mike", lastName: "kenan" }] console.log(personalList.map(({firstName,lastName}) => ({fullName: `${firstName} ${lastName}`})))

Here's How I Would Solve This Using For Loop. You Can Also Use Maps Like How @R4ncid Has Explained

 var desiredlist = [] var personalList = [{ firstName: "elena", lastName: "zakharova" }, { firstName: "alex", lastName: "farmanda" }, { firstName: "mike", lastName: "kenan" }] for (i=0;i<personalList.length;i++){ desiredlist.push({"fullname":personalList[i].firstName + " " + personalList[i].lastName})} console.log(desiredlist)

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