这可能是一个非常简单的问题,但我在最后一个小时内还没有找到答案。我有下面的数组,它总是在索引0中包含一个对象。为了方便以后使用,我想从数组中删除该对象,并将其直接存储为单个对象。也就是说,对象不应该再被包装在数组中。
当前状态:阵列
Array(1)
0:
bio: "Test"
id: 2
image: "http://localhost:8000/media/default.jpg"
user: 2
目标:目标
Object
bio: "Test"
id: 2
image: "http://localhost:8000/media/default.jpg"
user: 2
您只需将数组的第一个值分配给一个变量。记住,数组只存储对对象的引用,该引用可以存储在变量中,并以这种方式进行交互。
var arr = [
{
bio: "Test",
id: 2,
image: "http://localhost:8000/media/default.jpg",
user: 2
}
]
var obj = arr[0] // obj stores a reference to the object in arr
console.log(obj)
如果你想在不修改数组中对象的情况下处理数组外的对象,你可以";重复";它与排列运算符。
var arr = [
{
bio: "Test",
id: 2,
image: "http://localhost:8000/media/default.jpg",
user: 2
}
]
var obj = {...arr[0]} // obj stores a reference to an object identical to arr[0]
console.log(obj)