Javascript 将对象数组转换为保留内部的对象的对象
我还没有看到这个具体的解决方案,但如果存在,我希望有一个链接。我大致有以下几点:Javascript 将对象数组转换为保留内部的对象的对象,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,我还没有看到这个具体的解决方案,但如果存在,我希望有一个链接。我大致有以下几点: const obj = {"key": [ { "name": { "companyName": "Something" } }, { "otherThing": { "coolThing": "coolThingName" } }, ]} 这种格式的东西。我想把它改成: const obj = {"key": { { "name": { "companyName": "Something" } },
const obj = {"key":
[
{ "name": { "companyName": "Something" } },
{ "otherThing": { "coolThing": "coolThingName" } },
]}
这种格式的东西。我想把它改成:
const obj = {"key":
{
{ "name": { "companyName": "Something" } },
{ "otherThing": { "coolThing": "coolThingName" } },
}}
但出于某种原因,我一辈子都不知道该怎么做
以下是我目前掌握的代码:
const arr = [
{ 'value': 'val', 'another': 'yessir'},
{ 'value1': 'val1', 'another1': 'yessir1'},
{ 'value2': 'val2', 'another2': 'yessir2'},
{ 'value3': 'val3', 'another3': 'yessir3'},
];
const arrayToObject = (arry) => {
let newObj = {};
newObj = arry.reduce((acc, cur) => {
return { ...acc, ...cur };
}, {});
return newObj;
};
问题是,它将整个段返回到一个大对象中,而我需要保留子对象
编辑:
为了澄清,以下是我的动机:
我目前的elasticsearch查询如下
"query": {
"bool": {
"must": [
]}}
但“必须”的正确elasticsearch语法是:
我试图在代码中动态运行此转换这是可行的:
{
"name": { "companyName": "Something" } ,
"otherThing": { "coolThing": "coolThingName" }
}
const arr=[
{“名称”:{“公司名称”:“某物”},
{“其他事物”:{“酷事物”:“酷事物名称”},
],obj={};
arr.forEach(功能(项目){
常量键=对象键(项)[0];
obj[键]=项目[键];
})
控制台日志(obj)代码>对象是键值对,您有没有键的值
{
{ "name": { "companyName": "Something" } },
{ "otherThing": { "coolThing": "coolThingName" } },
}
请参阅此代码段中的错误:
const obj={“key”:
{
{“名称”:{“公司名称”:“某物”},
{“其他事物”:{“酷事物”:“酷事物名称”},
}}
不是有效的javascript对象。对象是key:value
对
像
第一个选项不只是主要语法吗?你想改变吗?数组和对象。第二个/想要的不是有效对象。我们可以知道原因吗???这是可行的:{“name”:{“companyName”:“Something”},“otherThing”:{“coolThing”:“coolThingName”}
@NinaScholz不可能有一个包含嵌套子对象的对象吗?它仍然是无效的,因为您有类似于{},{}
的东西,没有键是无效的,比如{key1:{},key2:{}
@JarredParr这是不可能的
{“key”:{“name”:{“companyName”:“Something”}、{“otherThing”:{“coolThing”:“coolThingName”}、}}{“key”:{1:{“name”:{“companyName”:“Something”}、{“otherThing”:{“coolThing”:“coolThing”:“coolThingName”}、}}、}}或{“key”:{companyName:“Something”},otherThing:{“coolThing”:“coolThingName”},}}
{
{ "name": { "companyName": "Something" } },
{ "otherThing": { "coolThing": "coolThingName" } },
}
{
{ "name": { "companyName": "Something" } },
{ "otherThing": { "coolThing": "coolThingName" } },
}
{
1: { "name": { "companyName": "Something" } },
2: { "otherThing": { "coolThing": "coolThingName" } },
}
const arr = [
{ 'value': 'val', 'another': 'yessir'},
{ 'value1': 'val1', 'another1': 'yessir1'},
{ 'value2': 'val2', 'another2': 'yessir2'},
{ 'value3': 'val3', 'another3': 'yessir3'},
];
const arrayToObject = (arry) => {
let newObj = {};
arry.forEach((item, index) => {
newObj[index] = item;
}, {});
return newObj;
};