从本质上讲,这就是我的API中的有效负载的样子。我想重塑数据,以便可以在前端动态显示数据而无需对列名之类的内容进行硬编码。对于我值得使用的是DRF,axios和react-redux。话虽如此,我想我只需要学习更多香草js:/
*故意在一个条目中具有与另一个条目不同的键数。
data =[
{
"id": 1,
"j_column": {
"name": "James",
"outside_id": 1,
"alt_name": "Jim",
"full_name": "James the third"
}
},
{
"id": 3,
"j_column": {
"name": "Dennis",
"outside_id": 57,
"alt_name": "Denny",
"full_name": "Dennis the third",
"nickname": "Denny the super star"
}
}]
newData =[
{
"id": 1,
"name": "James",
"outside_id": 1,
"alt_name": "Jim",
"full_name": "James the third"
},
{
"id": 3,
"name": "Dennis",
"outside_id": 57,
"alt_name": "Denny",
"full_name": "Dennis the third",
"nickname": "Denny the super star"
}]
答案 0 :(得分:0)
这是一种实现方法:
const data =[
{
"id": 1,
"j_column": {
"name": "James",
"outside_id": 1,
"alt_name": "Jim",
"full_name": "James the third"
}
},
{
"id": 3,
"j_column": {
"name": "Dennis",
"outside_id": 57,
"alt_name": "Denny",
"full_name": "Dennis the third",
"nickname": "Denny the super star"
}
}];
const newData = data.map((el) => {
const obj = {...el.j_column};
obj.id = el.id;
return obj;
});
console.log(newData);
答案 1 :(得分:0)
var new_data = [];
data.map(item => {
var obj = {};
Object.keys(item).map(itemKey => {
if (typeof item[itemKey] !== 'object') {
obj[itemKey] = item[itemKey]
}else
Object.keys(item[itemKey]).map(subItemKey => {
obj[subItemKey] = item[itemKey][subItemKey]
})
})
new_data.push(obj);
})
console.log(new_data);