从javascript中的对象制作新的对象数组 [英] Make new object array from object in javascript
本文介绍了从javascript中的对象制作新的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类似的对象:
let obj = {
type: 1
name: 'Test'
pr: 0
g: 1
}
我不想用它做这样的物体:
and i wan't to make like this object with it:
obj = [
{
title: "type",
value: 1,
},
{
title: "name",
value: "Test",
},
{
title: "pr",
value: 0,
},
{ title: "gr", value: 1 },
];
所以基本上第一个键是名字,第二个键是值.
so basically first key will be in name and second key will be value.
我尝试了什么?
newObj = Object.keys(obj).forEach(function (key) {
obj = {
name: key,
value: key,
};
});
这是可行的,但是它只给出对象的前2个值,而不是对象数组.
it's worked but it's give just first 2 value of the object and not makes object array.
所以输出是:
obj = {
name: type,
value: 1,
};
其他条目不可见.
我需要做什么?
推荐答案
You can use Object.entries
:
const obj = {
type: 1,
name: 'Test',
pr: 0,
g: 1
};
const res = Object.entries(obj)
.map(([title, value]) => ({title, value}));
console.log(res);
如果您不熟悉此语法:
([title, value]) => ({title, value})
它可以改写为:
function (x) { return { title: x[0], value: x[1] }; }
但是在上面的示例中,我使用了分解结构,从提供的键/值对中创建2个变量 title
和 value
.
But in the above example, I used a destructuring assignment to create 2 variables title
and value
from the provided key/value pair.
{title,value}
只是 {title:title,value:value}
的简写语法.
这篇关于从javascript中的对象制作新的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文