我知道这是一项非常简单的任务,但我看不出如何获得它。我总是得到一个包含三个对象的数组,但所有这些对象都是相同的。所以一点帮助真的很受欢迎。 我有一个具有一个键值对的对象数组,并希望将其转换为具有两个键值对的对象数组。
what_i_have = [
{apple: 1.5},
{lemon: 7},
{orange: 4}
]
what_i_want = [
{key: ’apple’, title: ‘apple’},
{key: ‘lemon’, title: ‘lemon’},
{key: ‘orange’, title: ‘orange’}
]
我在这里附上了我的最后一次尝试:
尝试1:
var attempt_1 = [];
var key_title_object = {};
for(var i in what_i_have){
key_title_object.key = Object.keys(what_i_have[i])[“0”];
key_title_object.title = Object.keys(what_i_have[i])[“0”];
attempt_1.push(key_title_object)
}
尝试2:
var myKeys = [];
for(var i in what_i_have){
var w = Object.keys(what_i_have[i]])["0"]
myKeys.push(w)
}
var attempt_2 = [];
var key_title_object = {};
for (var i in myKeys) {
key_title_object.key = myKeys[i];
key_title_object.title= myKeys[i];
attempt_2.push(key_title_object)
}
提前致谢!
答案 0 :(得分:3)
是的,您可以在此处找到一个有效的示例,请查看代码段:
var foobar = [
{apple: 1.5},
{lemon: 7},
{orange: 4}
]
var x = foobar.map(function (obj) {
var myKey = Object.keys(obj)[0]
return {key: myKey, title: myKey}
})
console.log(x)
输出结果为:
[
{
"key": "apple",
"title": "apple"
},
{
"key": "lemon",
"title": "lemon"
},
{
"key": "orange",
"title": "orange"
}
]
答案 1 :(得分:2)
在两次尝试中,问题是在循环内你重新使用在循环之前创建的相同key_title_object
对象。您推入数组的每个元素都指向同一个对象。
您只需在循环中创建一个新对象,以便每个数组元素引用不同的对象。与当前代码相比,最小的变化是将行var key_title_object = {};
移动到循环中:
what_i_have = [
{apple: 1.5},
{lemon: 7},
{orange: 4}
]
var attempt_1 = [];
for(var i in what_i_have){
var key_title_object = {}; // <-- this line was before the loop
key_title_object.key = Object.keys(what_i_have[i])["0"];
key_title_object.title = Object.keys(what_i_have[i])["0"];
attempt_1.push(key_title_object)
}
console.log(attempt_1);
更简洁的解决方案是使用array .map()
method,它调用每个数组元素提供一次的函数,并使用函数返回的值创建一个新数组:
what_i_have = [
{apple: 1.5},
{lemon: 7},
{orange: 4}
]
var result = what_i_have.map(function(v) {
var keyName = Object.keys(v)[0]
return { key: keyName, title: keyName };
});
console.log(result);
答案 2 :(得分:1)
a = [{ a: 1 }, { b: 2 }];
b = a.map(function(x) {
for (key in x) {
return { key: key, title: key };
}
});
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
<强>输出:强>
[{"a":1},{"b":2}]
[{"key":"a","title":1},{"key":"b","title":2}]
答案 3 :(得分:1)
您可以使用Array.prototype.map()
,Object.entries()
,Array.prototype.pop()
获取要在数组中返回的对象设置的当前对象的属性名称
var what_i_want = what_i_have.map(o => Object.entries(o).map(([key]) =>
({key:key, title:key})).pop())