gpt4 book ai didi

javascript - 如何将包含对象的对象转换为数组的数组?

转载 作者:行者123 更新时间:2023-12-03 02:30:32 25 4
gpt4 key购买 nike

如何转换此数据结构:

const data = {
0: {
campaign_lead_id: 2,
date: "2017-11-11T22:19:33.538000+00:00",
campaign_name: "IOT course fall 2017",
influencer_name: null,
influencer_email: "test_user_1@key"
},
1: {
campaign_lead_id: 1,
date: "2017-11-09T20:43:26.953000+00:00",
campaign_name: "IOT course fall 2017",
influencer_name: null,
influencer_email: "test_user_1@key"
}
}

到数组的数组,其中第一个数组包含键名称,其他数组包含键值,如下所示:

const CSVdata = [ 
['campaign_lead_id', 'date', 'campaign_name', 'influencer_name', 'influencer_email'],
['2', '2017-11-11T22:19:33.538000+00:00', 'IOT course fall 2017', null, 'test_user_1@2key.co'],
['1', '2017-11-09T20:43:26.953000+00:00', 'IOT course fall 2017', null, 'test_user_1@2key.co']
];

最佳答案

下面是我认为您可能正在寻找的代码。
将对象传递给 makeArray 函数,它将返回所需的数组。

const data = {
0: {
campaign_lead_id: 2,
date: "2017-11-11T22:19:33.538000+00:00",
campaign_name: "IOT course fall 2017",
influencer_name: null,
influencer_email: "test_user_1@key"
},
1: {
campaign_lead_id: 1,
date: "2017-11-09T20:43:26.953000+00:00",
campaign_name: "IOT course fall 2017",
influencer_name: null,
influencer_email: "test_user_1@key"
}
};
function makeArray(data){
var initialKeys = Object.keys(data);
var answer = [Object.keys(data[initialKeys[0]])];
for(let i=0;i<initialKeys.length;i++) {
answer.push(Object.values(data[i]));
}
return answer;
}
const CSVdata = makeArray(data);
console.log(CSVdata);

注意:仅对对象的对象有效。

关于javascript - 如何将包含对象的对象转换为数组的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com