问题描述
我有一个简单的JavaScript嵌套对象,如下所示。我不知道会有多少孩子,但这就是我接收到的数据的本质。 如何转换为预期结果?
原始数据嵌套的json
public static Uri getimageContentUri(Context context,File imageFile,String type) {
if (type != null && type.equals(Constants.IMAGE)) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,new String[]{MediaStore.Images.Media._ID},MediaStore.Images.Media.DATA + "=? ",new String[]{filePath},null);
if (cursor != null && cursor.movetoFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedpath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA,filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
} else {
return null;
}
}
} else if (type != null && type.equals(Constants.VIDEO)) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,new String[]{MediaStore.Video.Media._ID},MediaStore.Video.Media.DATA + "=? ",null);
if (cursor != null && cursor.movetoFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedpath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,"" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATA,filePath);
return context.getContentResolver().insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,values);
} else {
return null;
}
}
}
return null;
}
期望
{
"work": {
"children": {
"abc": {
"label": "Work address","name": "address"
},"xyz": {
"label": "Work phone","name": "phone"
},"efg": {
"children": {
"position": {
"label": "Work","name": "position"
},"employees": {
"label": "Number of employees","name": "employees"
}
}
}
}
}
}
我尝试过的是以下代码
{
work: {
"address": "","phone": "","details": {
"position": "","employees": ""
}
}
}
解决方法
您可以使用通用的map
函数和递归的transform
函数-
const map = (f,t) =>
Object.fromEntries(Object.entries(t).map(([ k,v ]) => [ k,f(v) ]))
const transform = (t = {}) =>
t.name
? ""
: map(transform,t.children || t)
const input =
{"work":{"children":{"address":{"component":"BaseInput","label":"Work address","name":"address"},"phone":{"component":"BaseInput","label":"Work phone","name":"phone"},"details":{"children":{"position":{"component":"BaseInput","label":"Work position","name":"position"},"employees":{"component":"BaseInput","label":"Number of employees","name":"employees"}}}}}}
console.log(transform(input))