将数组转换为对象类型
Posted
技术标签:
【中文标题】将数组转换为对象类型【英文标题】:Convert an Array into object type 【发布时间】:2021-09-09 22:18:39 【问题描述】:我想用键值对将数组转换为对象到特定对象。
[
"key": "out.of.stock",
"value": "out of stock"
,
"key": "buy.now",
"value": "BUY NOW"
,
"key": "notify.me",
"value": "You'll receive an email"
,
]
需要输出:
labels :
"out.of.stock" : "out of stock",
"buy.now" : "BUY NOW",
"notify.me": "You'll receive an email"
我尝试使用 loadash (keyBy) 但输出如下:
"out.of.stock":
"key": "out.of.stock",
"value": "out of stock"
,
"buy.now":
"key": "buy.now",
"value": "BUY NOW"
,
"notify.me":
"key": "notify.me",
"value": "You'll receive an email"
,
【问题讨论】:
使用Array.reduce
,
@Nur 这是错误的,他想通过labels
下配对
@Nur 这就是为什么你给所有答案一个minus
因为你的想法不同? ??????
这里重复了。 ***.com/q/42974735/14032355
【参考方案1】:
const data = [
"key": "out.of.stock",
"value": "out of stock"
,
"key": "buy.now",
"value": "BUY NOW"
,
"key": "notify.me",
"value": "You'll receive an email"
,
]
const result = data.reduce((acc, next) =>
acc.labels[next.key] = next.value
return acc
, labels: )
console.log(result)
【讨论】:
minus
?♂️ 怎么样【参考方案2】:
一个简单的就可以了。
var obj = labels:;
arr.forEach(e =>
obj.labels[e.key] = e.value;
);
var arr = [
"key": "out.of.stock",
"value": "out of stock"
,
"key": "buy.now",
"value": "BUY NOW"
,
"key": "notify.me",
"value": "You'll receive an email"
,
];
var obj = labels:;
arr.forEach(e =>
obj.labels[e.key] = e.value;
);
console.log(obj);
【讨论】:
【参考方案3】:let a=data.map((x)=>
let obj=
obj[x.key]=x.value
return obj
)
你可以先用map函数,再用keyby
【讨论】:
【参考方案4】:我会做Object.fromEntries(data.map((key, value) => [key, value]))
const data = [
"key": "out.of.stock",
"value": "out of stock"
,
"key": "buy.now",
"value": "BUY NOW"
,
"key": "notify.me",
"value": "You'll receive an email"
,
]
console.log(
Object.fromEntries(data.map((key, value) => [key, value]))
)
【讨论】:
【参考方案5】:我建议使用forEach()
方法,该方法将为每个数组元素执行一次提供的函数。在该函数中,您将通过在标签属性对象下应用具有相关值的键来为新对象分配。
const data = [
"key": "out.of.stock",
"value": "out of stock"
,
"key": "buy.now",
"value": "BUY NOW"
,
"key": "notify.me",
"value": "You'll receive an email"
,
];
let obj = "labels" :;
data.forEach(x => obj.labels[x.key] = x.value);
console.log(obj);
【讨论】:
【参考方案6】:const data = [
key: "out.of.stock",
value: "out of stock",
,
key: "buy.now",
value: "BUY NOW",
,
key: "notify.me",
value: "You'll receive an email",
,
];
const obj = label: ;
Object.values(data).map(( key, value ) =>
return (obj.label[key] = value);
);
console.log(obj)
【讨论】:
【参考方案7】:假设数组中的键/值顺序,试试Object.fromEntries(data.map(Object.values))
const data = [
"key": "out.of.stock",
"value": "out of stock"
,
"key": "buy.now",
"value": "BUY NOW"
,
"key": "notify.me",
"value": "You'll receive an email"
,
]
const labels = Object.fromEntries(data.map(Object.values));
console.log( labels )
【讨论】:
以上是关于将数组转换为对象类型的主要内容,如果未能解决你的问题,请参考以下文章
无法将 NumPy 数组转换为张量(不支持的对象类型浮点数)
无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)错误