我想从JSON创建一个新的array.问题是我不知道我将得到的JSON的 struct .它可能是任何东西.但我知道JSON的密钥,它将包含新数组所需的所有数据.例如,假设键是‘data’,它是包含我需要的所有数据的array.除此之外,我还必须在带有键‘data’的JSON数组中查找‘CustomerName’、‘CustomerAddress’和‘CustomerAge’.我将使用这些键的值创建新的array.因此,新数组So应该如下所示:
[
{
name: '', // it will be customerName from the JSON
address: '', // it will be customerAddress from the JSON
age: '', // it will be customerAge from the JSON
},
{
// more objects
}
]
请注意,CustomerName、CustomerAddress和CustomerAge可以存在于JSON中的"data"数组中的嵌套数组或对象中.所以我得go 找他们.
我为它创建了一个递归函数,但它返回一个空array.
这就是我try 过的:
function extractDataFromJSON(json, key) {
const result = [];
function findData(obj) {
if (Array.isArray(obj)) {
for (const item of obj) {
findData(item);
}
} else if (obj && typeof obj === 'object') {
if (key in obj) {
if (Array.isArray(obj[key])) {
for (const item of obj[key]) {
findData(item);
}
} else if (
'customerName' in obj[key] &&
'customerAddress' in obj[key] &&
'customerAge' in obj[key]
) {
const { customerName, customerAddress, customerAge } = obj[key];
result.push({
name: customerName || '',
address: customerAddress || '',
age: customerAge || '',
});
}
} else {
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] === 'object') {
findData(obj[prop]);
}
}
}
}
}
findData(json);
return result;
}
const jsonData1 = {
data: [
{
customerName: 'John Doe',
customerAddress: '123 Main St',
customerAge: 30,
},
{
customerName: 'Jane Smith',
customerAddress: '456 Maple Ave',
customerAge: 25,
},
// ... other data ...
],
};
// const jsonData2 = [
// {
// data: [
// {
// customerName: 'John Doe',
// customerAddress: '123 Main St',
// customerAge: 30,
// },
// {
// customerName: 'Jane Smith',
// customerAddress: '456 Maple Ave',
// customerAge: 25,
// },
// // ... other data ...
// ],
// }
// ];
// const jsonData3 = {
// data: [
// {
// customerName: 'John Doe',
// customerAge: 30,
// address: {
// customerAddress: '123 Main St',
// }
// },
// {
// customerName: 'Jane Smith',
// customerAge: 30,
// address: {
// customerAddress: '456 Maple Ave',
// }
// },
// ],
// };
const newArray = extractDataFromJSON(jsonData1, 'data');
console.log(newArray);
我还添加了另外两个对象作为测试,以判断我的函数是否也适用于这些类型的 struct .
任何帮助都将不胜感激.
更新
const jsonData1 = {
data: [
{
customerName: 'John Doe',
customerAddress: '123 Main St',
customerAge: 30,
},
{
customerName: 'Jane Smith',
customerAddress: '456 Maple Ave',
customerAge: 25,
},
// ... other data ...
],
data2: [
{
customerName: 'John Doe2',
customerAddress: '123 Mainsss St',
customerAge: 30,
},
{
customerName: 'Jane Smith3',
customerAddress: '456 Mapleaaa Ave',
customerAge: 25,
},
// ... other data ...
],
};