Home > Enterprise >  mapping an array of objects and sort result by string values
mapping an array of objects and sort result by string values

Time:09-09

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

CodePudding user response:

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

CodePudding user response:

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)

  • Related