首页 > 解决方案 > 在尝试获取所需的对象格式时获取空数据

问题描述

我有一个对象

"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);
    }
    }

标签: javascriptarraysobject

解决方案


你可以使用下面的。由于您标记了 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


推荐阅读