Javascript:更好的方式来读取相关的数组

时间:2017-10-27 05:41:00

标签: javascript

我有一个名为 values 的数组,其中有对象

let values = [
{name: "firstname", value: "Mike"},

{name: "lastname", value: "Smith "},

{name: "emailaddress", value: "mike@test.com"},

{name: "role", value: "123"}]


// Then I have code like this, which works

let editUser = {
    "firstnameofperson": values[0].value,
    "lastnameofperson": values[1].value,
    "emailaddress": values[2].value,
    "roleofperson": values[3].value,
}

console.log(editUser);

是否有更好的方法,而不是指定数组值[x] 索引等。

我正在使用ES6 btw

5 个答案:

答案 0 :(得分:3)

这样做的方法可能是:

(介意:' emailaddressofperson',不是' emailaddress',但它是连贯性的问题,你应该根据这个答案更改属性名称 - 甚至删除' ofperson'后缀)



Software_Engineer:Networking Software_Engineering Computer_Graphics Development Design  
Mechanical_Engineer:Automata 

let arr = [
    { name: "firstname"    , value: "Mike"          }
  , { name: "lastname"     , value: "Smith "        }
  , { name: "emailaddress" , value: "mike@test.com" }
  , { name: "role"         , value: "123"           }
]
  
let editUser = {};

arr.forEach( x => editUser[x.name+'ofperson'] = x.value )

console.log(editUser);




答案 1 :(得分:0)

您可以按如下方式修改数组。

var values=[];

values["firstname"]={name: "firstname", value: "Mike"};
values["lastname"]={name: "lastname", value: "Smith "};
values["emailaddress"]={name: "emailaddress", value: "mike@test.com"};
values["role"]={name: "role", value: "123"};
    
console.log(values["firstname"].value);

答案 2 :(得分:0)

在这种情况下,我通常使用转换函数。

对于你的例子,它可能是:

function translate (d) {
    let p={};
    d.map(r=>p[r.name]=r.value);
    return p;
}

如果您更喜欢内衬:

let output = ((d)=>{let p={};d.map(r=>p[r.name]=r.value);return p})([
    {name: "firstname", value: "Mike"},
    {name: "lastname", value: "Smith "},
    {name: "emailaddress", value: "mike@test.com"},
    {name: "role", value: "123"}
]);

但是,除非你只需要转换单个项目,为了便于阅读,我宁愿采用第一种方法,在这种情况下,我更喜欢你的版本(我发现事实并非如此)。

答案 3 :(得分:0)

有一个名为Map的ES6对象,它包含键:值对,并且有一种使用.get获取值的方法。这与您的对象不同,但是另一种方法。

//your data
let data = [{
    name: "firstname",
    value: "Mike"
  },

  {
    name: "lastname",
    value: "Smith "
  },

  {
    name: "emailaddress",
    value: "mike@test.com"
  },

  {
    name: "role",
    value: "123"
  }
];

//turn the data into their own arrays for the map object
let newArr = data.map((i) => [i.name, i.value]);
//create the map object
let testMap = new Map(newArr);
//shows the map obj
console.log(testMap)
  /*
  0 :{"firstname" => "Mike"}
  1 :{"lastname" => "Smith "}
  2 :{"emailaddress" => "mike@test.com"}
  3 :{"role" => "123"}
  */
  //an example of getting the firstname
  console.log(testMap.get("firstname")); //returns "Mike"

答案 4 :(得分:-1)

试试这个:

(Unique_ID,) = (x.text_content() for x in tree.xpath('//a[@class="property-
value__link--muted rui-button-brand property-value__btn-listing"]'))