javascript - 在尝试获取所需的对象格式时获取空数据
问题描述
我有一个对象
"data" : [
{
"name" : "Heading",
"text" : "Text Heading",
"type" : "string",
"values" : [
"Arthur"
]
},
{
"name" : "Source",
"text" : "Source Reference",
"type" : "string",
"values" : [
"Jhon"
]
},
{
"name" : "Place",
"text" : "Bank Building",
"type" : "string",
"values" : [
"Mark"
]
},
{
"name" : "Animal",
"text" : "Branch",
"type" : "string",
"values" : [
"Susan"
]
}
]
有一个函数我正在传递对象和一个数组作为参数
fieldArray=["Heading", "Animal"]
myFunction(fieldArray, data){
... your code here
}
我需要以以下格式获取输出,其中我必须使用 myArray 中的字段和数据的名称键来搜索对象。然后我需要将搜索到的对象的值放在下面的格式中
[{
"id": 1,
"cells": [{
"id": "ConstId",
"cellContent": "Heading"
},
{
"id": "ConstValue",
"cellContent": "Arthur"
}
]
},
{
"id": 2,
"cells": [{
"id": "ConstId",
"cellContent": "Animal"
},
{
"id": "ConstValue", //a constant field name as ConstValue
"cellContent": "Susan" // the value of the second field in the myArray from object with name Animal
}
]
}
]
我试过这个
const getFormattedData = (fieldArray: any, data: any) => {
let innerData: any = [];
for (let i=0; i<fieldArray.length; i++){
const indexNumber = data.find((key: any) => key.name === fieldArray[i])
if(indexNumber != undefined){
innerData.push({
id: i+1,
cells:[{
id: 'inquiryName',
cellContent: indexNumber.name
},
{
id: 'value',
cellContent: indexNumber.values.toString()
}
]
})
}
console.log('innerData :>> ', innerData);
}
}
解决方案
你可以使用下面的。由于您标记了 javascript,因此在 JS 中发布答案。
function formatData(data, fieldArray) {
let ret = [];
fieldArray.forEach((field, i) => {
let dataObj = data.filter(d => d.name === field)[0]
if( dataObj ) {
ret.push({
"id": 1,
"cells": [{
"id": "ConstId",
"cellContent": field
},
{
"id": "ConstValue",
"cellContent": dataObj.values[0] //Put whole obj or just first
}
]
})
}
})
return ret;
}
链接到plnkr
推荐阅读
- javascript - 不同应用程序中的电子邮件样式变化
- python - 从同一列中的数据行中减去数据行
- postgresql - 在函数中声明具有相同名称的参数或变量时,postgresql 不检测重复名称
- python - 在 python 中创建基于运算符优先级的字典
- django - 为什么在管理员/中显示用户配置文件的字段(liked_songs),但在我查询数据库时不显示
- go - 无法从 github 安装 cmd 版本的 c4
- flutter - Flutter InAppWebView - 在浏览器中打开其他网站地址
- lambda - 从 Java 中的方法返回 Lambda 返回值
- html - 显示图例文本时防止容器增长
- windows - 在 ARM64 Windows 系统上,如何确保访问注册表的特定 WOW 部分?