简体   繁体   中英

mapping an array of objects and sort result by string values

i hope i can find help hier.
How can i get a full name form this array of Objects like this format: "Title" "LastName", "Name"??

selectsUsers = [
    {
      column: "Name",
      value: "Martin",
      gqlName:"TMP_name"
    },
    {
      column: "Lastname",
      value: "Anderson",
      gqlName:"TMP_lastname"
    },
    {
      column: "Title",
      value: "Sir",
      gqlName:"TMP_title"
    },
  ];

I'm using a map and join methods to return the fullname from the object's entries:

let pathView = this. selectsUsers
            .map((item) => {
              return _.get(this.obj, this.dtoName + "." + item.gqlName);
            })
            .join(", ");

What i go is this: "Martin, Anderson, Sir" What i want to achieve is this: "Sir Anderson, Martin"

i would be so thankfull if someone can help

You could take an object with the wanted properties and build a string from the key/value pairs.

 const getName = ({ Name, Lastname, Title = '' }) => `${Title}${Title && ' '}${Lastname}, ${Name}`, user = [{ column: "Name", value: "Martin" }, { column: "Lastname", value: "Anderson" }, { column: "Title", value: "Sir" }], result = getName(Object.fromEntries(user.map(({ column, value }) => [column, value]))); console.log(result);

You can use Array.prototype.reduce() in combination with String.prototype.replace() to do something like:

 const selectsUsers = [{ column: "Name", value: "Martin", }, { column: "Lastname", value: "Anderson", }, { column: "Title", value: "Sir", }, ]; const fullName = selectsUsers.reduce((outStr, {column, value}) => { return outStr.replace(`{${column}}`, value);; }, '{Title} {Lastname}, {Name}'); console.log(fullName)

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