我想知道如何使用javascript从现有对象创建新对象。
我有对象obj
和数组arr
,因此需要以预期的输出格式创建对象。
var result =getObj("en", obj);
function getObj(lang, obj){
var newobj = {};
newobj['url'] = "/"+ lang +"/"+obj[lang].map(e=>e.faq);
var s ={lang: lang, url: newobj.url};
newobj['links']=[s];
return newobj;
}
var obj={
"en": [{
"faq": "faq",
"about": "about"
}],
"hi": [{
"faq": "aksar-poochhe-jaane-vaale",
"about": "hamaare-baare"
}]
}
预期输出:
getObj("en", obj);
//expected result
{
"url": "/en/faq",
"links": [
{ lang: 'en', url: '/en/faq' },
{ lang: 'hi', url: '/hi/aksar-poochhe-jaane-vaale' }
]
},{
"url": "/en/about",
"links": [
{ lang: 'en', url: '/en/about' },
{ lang: 'hi', url: '/hi/hamaare-baare' }
]
}
getObj("hi", obj);
//expected result
{
"url": "/hi/aksar-poochhe-jaane-vaale",
"links": [
{ lang: 'en', url: '/en/faq' },
{ lang: 'hi', url: '/hi/aksar-poochhe-jaane-vaale' }
]
},{
"url": "/hi/hamaare-baare",
"links": [
{ lang: 'en', url: '/en/about' },
{ lang: 'hi', url: '/hi/hamaare-baare' }
]
}
答案 0 :(得分:1)
您需要使用嵌套循环。主循环返回对象的顶级数组,内部循环在每个对象内创建links
数组。
function getObj(lang, obj) {
const langObj = obj[lang][0];
return Object.keys(langObj).map(key => ({
url: `/${lang}/${langObj[key]}`,
links: Object.keys(obj).map(l => ({
lang: l,
url: `/${l}/${obj[l][0][key]}`
}))
}));
}
var obj = {
"en": [{
"faq": "faq",
"about": "about"
}],
"hi": [{
"faq": "aksar-poochhe-jaane-vaale",
"about": "hamaare-baare"
}]
};
console.log(getObj("en", obj));
console.log(getObj("hi", obj));