我有一个对象,我想将其转换为对象数量
看到这是一个对象-
[{
"type_width": "245",
"type_height": "60",
"type_size": "21"
}]
,并希望将其转换为:
[{ "Type Width": "245"},{"Type Height": "60"},{"Type Size": "21"}]
答案 0 :(得分:3)
您可以使用Object.entries和map
let arr = [{ "width": "245","height": "60","size": "21"}]
let op = Object.entries(arr[0]).map(([key,value]) => ({[key]: value}) )
console.log(op)
答案 1 :(得分:1)
您可以使用Array.flatMap()
来迭代对象,并将结果展平为单个数组。使用Object.entries()
将每个对象转换为键/值对的数组,并将Array.map()
对转换为一个对象。
const data = [{"width":"245","height":"60","size":"21"}]
const result = data.flatMap(o => // iterate the objects and merge the results to a single array
Object.entries(o) // convert each object to an array of key/value pairs
.map(([k, v]) => ({ [k]: v })) // convert each pair to an object
)
console.log(result)
答案 2 :(得分:0)
如果已经在变量中:
let obj = [{
width: "245",
height: "60",
size: "21"
}]
console.log(
Object.keys(obj[0]).map(k => ({[k] : obj[0][k]}))
)