在Javascript对象中查找并替换键

时间:2018-10-26 18:36:53

标签: javascript reactjs

我正在访问一个返回的JSON,如下所示:

[
{
    "itemType": "SelectionTitle",
    "name": "1105F.MID",
    "active": true,
    "isFactoryDefault": false,
    "factoryCode": "",
    "seasons": [],
    "denominations": [],
    "groups": [],
    "length": 0,
    "_id": "5ada2217c114ca048e1db9b0",
    "created_by": "5ab57289d8d00507b29a3fdd",
    "selectionFile": {
        "itemType": "SelectionFile",
        "name": "1105F.MID",
        "active": true,
        "isFactoryDefault": false,
        "selectionType": "Music",
        "sfzFile": "",
        "destination": "/data/uploads",
        "encoding": "7bit",
        "fieldname": "file",
        "filename": "782f49a7cd72b865b4e2d286816792e7",

...
        "found": true,
        "flError": false,
        "error_strings": [],
        "_id": "5ada2217c114ca048e1db9af",
        "created_by": "5ab57289d8d00507b29a3fdd",
        "slug": "1105fmid",
        "__v": 0,
        "createdAt": "2018-04-20T17:23:35.216Z",
        "updatedAt": "2018-04-20T17:23:35.788Z",
        "selectionTitles": null,
        "id": "5ada2217c114ca048e1db9af"
    },
    "slug": "1105fmid",
    "createdAt": "2018-04-20T17:23:35.285Z",
    "updatedAt": "2018-04-20T17:23:35.285Z",
    "__v": 0,
    "id": "5ada2217c114ca048e1db9b0"
}, ...

我正在使用的react-select节点模块采用键“标签”来生成填充的下拉列表。

JSON是来自网络的,所以我无法控制JSON的设置方式。如何解析JSON以查找“名称”的所有实例并将该键替换为“标签”?

例如,应将“名称”:1105F.MID”更改为“标签”:“ 1105.MID”

将整个内容转换为字符串并使用javascript方法find / replace效率低下吗?

3 个答案:

答案 0 :(得分:2)

假设您的JSON数组存储在变量false中:

true

这足以将数组中每个项目的data属性复制为data.forEach(item => item.label = item.name) 属性。

答案 1 :(得分:1)

我创建了一个函数 replace()来处理每个对象和嵌套对象,如果找到了“名称”属性,它将添加属性“标签”。请查看它是否对您有用。

Function num_words(ByVal text As String)
Dim txt_split
txt_split = Split(text, " ")

Dim total_words As Long
total_words = 0

Dim i As Long
For i = LBound(txt_split) To UBound(txt_split)
    If Not IsNumeric(txt_split(i)) Then
        total_words = total_words + 1
    End If
Next i
num_words = total_words
End Function

答案 2 :(得分:0)

依靠服务器响应的结构不好;特别是当您说您无法控制它时。更好的方法是始终解析服务器响应,构造使react-select组件正常工作并仅传递它所需的任何内容。