I have an array of objects and I need to add a key to the object as well as the parent array/object with the same values.(我有一个对象数组,我需要向该对象以及具有相同值的父数组/对象添加一个键。)
Below is my implementation:(下面是我的实现:)
const data = [{ "label": "Grand Parent 1", "index": 0, "code": "GRAND_PARENT_1", "defaultCollapsed": true, "items": [{ "id": 1, "items": [{ "id": 100, "label": "Child 1", "url": "#CHILD_1", "code": "CHILD_1" }, { "id": 200, "label": "Child 2", "url": "#CHILD_2", "code": "CHILD_2" }, { "id": 300, "label": "Child 3", "url": "#CHILD_3", "code": "CHILD_3" }, { "id": 400, "label": "Child 4", "url": "#CHILD_4", "code": "CHILD_4" } ], "defaultCollapsed": false, "label": "Parent 1" }, { "id": 2, "items": [], "defaultCollapsed": true, "label": "Parent 2" }, { "id": 3, "items": [], "defaultCollapsed": true, "label": "Parent 3" }, { "id": 4, "items": [], "defaultCollapsed": true, "label": "Parent 4" } ] }, { "label": "Grand Parent 2", "index": 1, "code": "GRAND_PARENT_2", "defaultCollapsed": true, "items": [] }, { "label": "Grand Parent 3", "index": 2, "code": "GRAND_PARENT_3", "defaultCollapsed": true, "items": [] } ] const filterData = (data, value) => { const r = _.filter(data, item => { const dataMap = _.map(item.items, subItem => { const subItemMap = _.map(subItem.items, subsecItem => { if(subsecItem.code === value) { return item } }) }) }) return r; } console.log(filterData(data, 'CHILD_1'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
So I want to add a key called selected: true
to the child as well as the parent objects when the value to the function is CHILD_1;(因此,我想为该子项以及父项对象添加一个名为selected: true
的键(当函数的值为CHILD_1时);)
Expected Output:(预期产量:)
[
{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"selected": true,
"items": [
{
"id": 1,
"items": [
{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
"selected": true
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": false,
"label": "Parent 1",
"selected": true
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
Please advice.(请指教。) I was stuck at trying to filter the data based on the value.(我被困在尝试根据值筛选数据。)
ask by a2441918 translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…