如何将一个或所有Object.keys复制到新的对象文字中 例如:
let obj = [
{
name: "value1",
age: "value2",
gender: "value3",
group: "cat"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "cat"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "dog"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "dog"
},
]
输出是这样的:
{
cat: { name: "value1", age: "value2"},
dog: { name: "value1", age: "value2"}
}
我们应该使临时对象复制它,然后将其分配给newObj吗? 我很想知道解释,所以我会理解的, 只是举例,如果组中有很多同类组,我们应该为此创建一个函数吧?
答案 0 :(得分:1)
您可以遍历数组中的每个项目,处理数据,并将结果分配给新对象:
let array_of_objects = [{
name: "value1",
age: "value2",
gender: "value3",
group: "cat"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "cat"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "dog"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "dog"
},
]
let result = {};
array_of_objects.forEach(animal =>
result[animal.group] = {
name: animal.name,
age: animal.age
}
);
console.log(result);
说明:
animal
。result
通过扩展符号...result
获得其先前的值,并由于代码的[animal.group]
部分而获得了新的键。请注意,此表示法在正方形之间,因为需要评估密钥。注意:通过这种实现,新的cat
值将例如覆盖先前的值,但是当您的数据集中有两个cat
时,您不清楚要做什么。
答案 1 :(得分:1)
您可以使用Object.assign
(许多替代方法之一):
const array_of_objects = [{ name: "value1", age: "value2", gender: "value3", group: "cat" }, { name: "value1", age: "value2", gender: "value3", group: "cat" }, { name: "value1", age: "value2", gender: "value3", group: "dog" }, { name: "value1", age: "value2", gender: "value3", group: "dog" }, ];
const result = {};
for (const obj of array_of_objects) result[obj.group] = Object.assign({}, obj);
console.log(result);
Object.assign
将评估作为第二(第三,...)参数给出的对象的(可枚举)属性,并将这些属性存储在作为第一参数传递的对象中。返回结果对象,并因此表示(浅)副本。
使用更现代的传播语法也可以实现同样的目的。
如果您只想复制一些特定的属性,而不是全部,那么您可以对每个键使用简单的分配。作为答案,这并不是一个真正的挑战,我想您在循环主体中编写以下代码没有问题:
const copy = {};
copy.name = obj.name;
// copy anything else here ...
result[obj.group] = copy; // store it in the overall result object
如果您想要更酷的东西,那么我们回到ES6语法:
const {name, age} = obj;
result[obj.group] = {name, age};
答案 2 :(得分:0)
使用Array#reduce()
和对象分解
const res = data.reduce((a, {group, gender, ...rest})=>{
a[group] = {...rest}
return a
},{})
console.log(res)
<script>
const data = [{
name: "value1",
age: "value2",
gender: "value3",
group: "cat"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "cat"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "dog"
},
{
name: "value1",
age: "value2",
gender: "value3",
group: "dog"
},
]
</script>