简体   繁体   English

映射对象数组并按字符串值对结果进行排序

[英]mapping an array of objects and sort result by string values

i hope i can find help hier.我希望我能找到帮助hier。
How can i get a full name form this array of Objects like this format: "Title" "LastName", "Name"??我怎样才能从这种格式的对象数组中获得全名:“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:我正在使用 map 和 join 方法从对象的条目中返回全名:

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"我的 go 是这样的:“Martin,Anderson,Sir” 我想要实现的是:“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.您可以使用具有所需属性的 object 并从键/值对构建字符串。

 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:您可以将Array.prototype.reduce()String.prototype.replace()结合使用来执行以下操作:

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM