我有初始数组,应该对其进行迭代并应该创建新对象。初始数组为:
let array = [
{key: "key1", translation: "some text 1"},
{key2: "key2", translation: "some text 2"},
{key3: "key3", translation: "some text 3"},
];
然后我对其进行迭代并创建对象:
const final = {};
const language = "eng";
for (let item of array) {
final[item.key] = {};
final[item.key][language] = item.translation;
}
它最终成为对象:
{
key1: {
eng: "Some text 1"
},
key2: {
eng: "Some text 2"
},
key3: {
eng: "Some text 3"
}
}
我需要将这些外键(key1
,key2
和key3
)用双引号引起来,以便最终对象变为:
{
"key1": {
eng: "Some text 1"
},
"key2": {
eng: "Some text 2"
},
"key3": {
eng: "Some text 3"
}
}
答案 0 :(得分:1)
我认为您正在寻找JSON.stringify()
。让我们在这里看看:
let array = [
{key: "key1", translation: "some text 1"},
{key2: "key2", translation: "some text 2"},
{key3: "key3", translation: "some text 3"},
];
console.log(JSON.stringify(array));
答案 1 :(得分:1)
如果您使用JSON.stringify()
来获取数组的JSON字符串,则该值会被完美引用:
let array = {
key1: {
eng: "Some text 1"
},
key2: {
eng: "Some text 2"
},
key3: {
eng: "Some text 3"
}
};
console.log(JSON.stringify(array));
答案 2 :(得分:1)
您编写的循环不正确。应该是这样的:
let array = [
{key: "key1", translation: "some text 1"},
{key2: "key2", translation: "some text 2"},
{key3: "key3", translation: "some text 3"},
];
const final = {};
const language = "eng";
for (let item of array) {
final[Object.values(item)[0]] = {};
final[Object.values(item)[0]][language] = item.translation;
}
console.log(JSON.stringify(final));
此外,不要忘记使用JSON.stringify()
进行字符串化。
答案 3 :(得分:0)
let array = [
{key: "key1", translation: "some text 1"},
{key: "key2", translation: "some text 2"},
{key: "key3", translation: "some text 3"},
];
let data={};
array.map(item => {
let d=item.key;
let da=item.translation;
data[d]=da;
})
}
console.log(data)