Javascript 如何在数组的对象中连接两个键?Js
我需要连接两个键,因为我想在一个键用户名中连接名字和姓氏。 json的示例数组Javascript 如何在数组的对象中连接两个键?Js,javascript,Javascript,我需要连接两个键,因为我想在一个键用户名中连接名字和姓氏。 json的示例数组 arr = [ {id: 1 , first_name: Test , last_name: Test2 , city: "Berlin" } , {id: 2 , first_name: Alan, last_name: Test5 , city: "Minsk" } , ] 我需要创建新的对象或相同的对象,以创建任意思维 arr = [ { id: 1 , fir
arr = [
{id: 1 , first_name: Test , last_name: Test2 , city: "Berlin" } ,
{id: 2 , first_name: Alan, last_name: Test5 , city: "Minsk" } ,
]
我需要创建新的对象或相同的对象,以创建任意思维
arr = [
{ id: 1 , first_name: Test , last_name: Test2 , city: "Berlin", username: "Test Test2" } ,
{ id: 1 , first_name: Alan, last_name: Test5 , city: "Berlin", username: "Alan Test5" } ,
]
您只需使用将username
属性添加到该数组中的每个对象:
let ari=[
{id:1,名字:“Test”,姓氏:“Test2”,城市:“Berlin”},
{id:2,名字:“艾伦”,姓氏:“Test5”,城市:“明斯克”}
];
ary.forEach((obj)=>
{
obj.username=`${obj.first\u name}${obj.last\u name}`;
});
控制台日志(ary)代码>
const arr=[
{id:1,名字:'Test',姓:'Test2',城市:'Berlin'},
{id:2,名字:'Alan',姓氏:'Test5',城市:'Minsk'},
];
arr.forEach(项目=>{
item.username=`${item.first\u name}${item.last\u name}`;
})
控制台日志(arr)代码>首先,键first\u name
和last\u name
必须是字符串,对吗
let arr = [
{ id: 1, first_name: "Test", last_name: "Test2", city: "Berlin" },
{ id: 2, first_name: "Alan", last_name: "Test5", city: "Minsk" },
]
您可以简单地使用forEach
或for
循环遍历数组
然后可以为对象定义一个新键
arr.forEach(element => {
element['username'] = element.first_name + ' ' + element.last_name;
})
实际上,最好使用element.hasOwnProperty('last\u name')
检查键first\u name
和last\u name
是否存在。如果要创建新数组,应该使用array\map
而不是array\forEach
。您还应该深度复制所有内部对象(一种简单的方法是Object.parse(Object.stringify(oldObject))
我还假设first\u name
,last\u name
属性的值是字符串(没有引号),并且id和city不会合并
var-arr=[{
id:1,
名字:“测试”,
姓氏:“Test2”,
城市:“柏林”
},
{
id:2,
名字:“艾伦”,
姓氏:“Test5”,
城市:“明斯克”
},
];
var newArr=arr.map(功能(项目){
var newItem=JSON.parse(JSON.stringify(item));
newItem.username=newItem.first\u name+“”+newItem.last\u name;
返回新项目;
});
console.log(newArr);
您可以使用.map
const arr=[
{id:1,名字:'Test',姓氏:'Test2',城市:'Berlin'},
{id:2,名字:'Alan',姓氏:'Test5',城市:'Minsk'}
]
常数res=arr.map(el=>({
…呃,
用户名:[el.first\u name,el.last\u name]。加入(“”)
}))
console.log(res)
您尝试过什么吗?什么不起作用?为什么输出上的id
和city
都是相同的?是Test
和Test2
和Alan
和Test5
您在某处定义的一些变量?或者它们也应该是字符串吗?我尝试使用object.assign不做任何工作。这只是我的示例我的code.Sample.Test和Test 2在同一个数组中您可以使用reduce
方法。对于您的代码,我认为这将起作用-arr.reduce((acculator,currentValue)=>{currentValue.username=`${currentValue.first_name}${currentValue.last_name};acculator.push(currentValue);return acculator;},[]);但正如我所看到的,first_name和last_name不是字符串类型。请注意,这仅在first_name和last_name是字符串类型时才起作用。请注意,提供的数组无效,我将first_name和last name更改为字符串以使示例生效。element['username']
?向对象添加键username
。它可以工作,试试看。是的……它可以……元素也可以。username
@JaromandaX元素['username']
和元素。用户名
都是有效的;编码风格中的个人偏好不应构成否决正确答案的理由。没有理由对元素进行元素['username']
而不是元素。用户名
。使用点更干净、更容易混淆。(大多数IDE警告不要不必要地使用[]
符号)为什么是newArr?OP想要相同的arr
@JaromandaX问题是我需要创建新对象和或者相同的,听起来像是备份。@JaromandaX OP到底在哪里说他需要就地更改?@SebastianKaczmarek我也不知道他是如何解释的..arr=现有数组
…arr=添加的元素
…查看arr
是如何成为同一变量的