如何在数组数组中连接数组的字符串属性,并在每个数组中创建一个新属性

时间:2018-04-24 22:55:12

标签: javascript jquery arrays reactjs javascript-objects

我有一个数组数组,如下所示:

UserList=[
[name:"user1", type:"admin", location:"NY", expired:"NO"],
[name:"user2", type:"poweruser", location:"CO", expired:"NO"],
[name:"user3", type:"admin", location:"SF", expired:"NO"],
]

我想添加三个属性名称,类型和位置,并在每个单独的数组中创建一个新属性,如下例中的属性“AllProps”:

期望的输出:

UserList=[
[name:"user1", type:"admin", location:"NY", expired:"NO",AllProps:"user1adminNY"],
[name:"user2", type:"poweruser", location:"CO", expired:"NO",AllProps:"user1poweruserCO"],
[name:"user3", type:"admin", location:"SF", expired:"NO", AllProps:"user1adminSF"],
]

我可以使用Loadash执行此操作吗?最好和最快的方法是什么?

3 个答案:

答案 0 :(得分:2)

您正在使用{}但数组应为[]。您还需要在对象中使用:而不是=

var userList= [
{name: "user1", type: "admin", location: "NY", expired: "NO"},
{name: "user2", type: "poweruser", location: "CO", expired: "NO"},
{name: "user3", type: "admin", location: "SF", expired: "NO"}
];

var output = userList.map(user => {
   user.AllProps = user.name + user.type + user.location;
   return user;
});

// Short hand
var output = userList.map(user => ({ ...user, AllProps: user.name + user.type + user.location}));

console.log('output:', output);

答案 1 :(得分:1)

我认为这样的事情你需要:

_.forEach(UserList, function(u){
  var allPropValues = "";
  _.forOwn(u, function(value, key) {
     if(key !== 'expired') {
        allPropValues += value;
     }
  });  
  u.AllProps = allPropValues;
});



var UserList=[
{name:"user1", type:"admin", location:"NY", expired:"NO"},
{name:"user2", type:"poweruser", location:"CO", expired:"NO"},
{name:"user3", type:"admin", location:"SF", expired:"NO"},
];
console.log({before: UserList});

_.forEach(UserList, function(u){
  var allPropValues = "";
  _.forOwn(u, function(value, key) {
     if(key !== 'expired') {
        allPropValues += value;
     }
  });  
  u.AllProps = allPropValues;
});

console.log({after: UserList});

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.9/lodash.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

根据您的要求,只想修改现有数组而不返回新数组,只需迭代数组并添加键/值对:

var UserList = [
	{name: "user1", type: "admin", location: "NY", expired: "NO"},
	{name: "user2", type: "poweruser", location: "CO", expired: "NO"},
	{name: "user3", type: "admin", location: "SF", expired: "NO"},
];

UserList.forEach(function(x){
	x["AllProps"] = x.name + x.type + x.location;
});	

console.log(UserList);

upvoted答案可以正常使用,但不需要返回任何内容。