我有一个JavaScript对象,其中一个属性是一个数组。我想修改该对象以创建几乎相同的对象,除了一个属性是String之外。
类似join方法可用于将数组更改为字符串(例如console.log(elements.join('-'))
)。
但是如何创建一个与旧对象相同但具有一个不同属性(即字符串而不是数组)的新对象?
例如,我有一个对象carOriginal:
{
"make": "Ford",
"model": "F150",
"features": [
"windows",
"seatbelts"
]
}
...,然后我要创建这个对象carNew:
{
"make": "Chevy",
"model": "Tahoe",
"features": "windows,seatbelts"
}
答案 0 :(得分:1)
如果使用ES6,则可以分解原始文件并添加新功能值:
const data = {
"make": "Ford",
"model": "F150",
"features": [
"windows",
"seatbelts"
]
}
const other = {...data, features: data.features.join()}
console.log(other)
答案 1 :(得分:0)
尝试一下:
const obj = {
"make": "3",
"model": "2019-07-17",
"features": [
"windows",
"seatbelts"
]
}
const result = Object.assign({},obj, {features: obj.features.join()});
console.log(result);
答案 2 :(得分:0)
您可以使用object rest and spread syntax将其余的密钥收集到一个单独的浅表副本中,修改后的属性将分配给该浅表副本:
const carOriginal = {
"make": "Ford",
"model": "F150",
"features": [
"windows",
"seatbelts"
]
};
function transform ({ features, ...keys }) {
return { ...keys, features: features.join() };
}
const carNew = transform(carOriginal);
console.log(carNew);
答案 3 :(得分:0)
如果您不知道属性的名称,则必须检查每个值以查看其是否为数组:
function subJoin(obj) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (Array.isArray(obj[prop])) {
obj[prop] = obj[prop].join(',');
}
}
}
return obj;
}
let input = {
"make": "Ford",
"model": "F150",
"features": [
"windows",
"seatbelts"
]
}
let output = subJoin(input);
console.log(output); /// --> { "make": "Chevy", "model": "Tahoe", "features": "windows,seatbelts" }