[英]spread operator to copy values to nested object dynamically using array forEach loop
This is the code I made, its actually from the react project I am working on, where I wanted to add more key-value pairs under particular keys.这是我制作的代码,它实际上来自我正在处理的 react 项目,我想在特定键下添加更多键值对。 So I made a similar sample code to know how to do it, but unfortunately, I can't find a solution on the internet.
所以我做了一个类似的示例代码来知道怎么做,但很遗憾,我在网上找不到解决方案。 Please help
请帮忙
const filteredSearchItems=[{
"id":"das",
"value":45
},
{
"id":"das3",
"value":48
},
{
"id":"das4",
"value":47
},
{
"id":"das5",
"value":46
},
]
let savedFilter = "";
const savefilter = () => {
const saveName = "fooCriteria";
filteredSearchItems.forEach(item => {
if (!savedFilter) {
savedFilter={ [saveName]: { [item.id]: item.value } };
} else
savedFilter={...savedFilter.saveName,...{
...savedFilter.saveName,
...{ [item.id]: item.value }
}};
});
};
savefilter();
console.log("savedFilter :",savedFilter)
output输出
savedFilter : { das5: 46 }
My Expected output that I wanted我想要的预期输出
{ fooCriteria: { das: 45, das3: 48, das4: 47, das5: 46 } }
PS: I wanted to give fooCriteria as savename variable there is a reason. PS:我想给 fooCriteria 作为 savename 变量是有原因的。 since the name of the object is determined by the user
因为对象的名称是由用户决定的
const saveName = document.getElementById("seachSaveInput").value;
const filteredSearchItems=[{"id":"das","value":45},{"id":"das3","value":48},{"id":"das4","value":47},{"id":"das5","value":46}]; let fooCriteria = filteredSearchItems.reduce((acc,{id,value})=>(acc[id]=value,acc),{}); console.log({fooCriteria})
You can use reduce
method您可以使用
reduce
方法
instead of forEach
reduce
makes more sense.而不是
forEach
reduce
更有意义。
const filteredSearchItems = [ { 'id': 'das', 'value': 45 }, { 'id': 'das3', 'value': 48 }, { 'id': 'das4', 'value': 47 }, { 'id': 'das5', 'value': 46 } ]; const savedFilter = {}; const saveFilter = () => { const saveName = 'fooCriteria'; savedFilter[saveName] = filteredSearchItems.reduce((saved, item) => { saved[item.id] = item.value; return saved; }, savedFilter[saveName] || {}); }; saveFilter(); console.log('savedFilter :', savedFilter);
I'd do a shallow copy with spread notation:我会用扩展符号做一个浅拷贝:
// If you want to add to the [saveName] entry if it exists:
savedFilter = {...savedFilter, [saveName]: savedFilter ? {...savedFilter[saveName]} : {}};
// If you want to *replace* the [saveName] entry, not add to it:
savedFilter = {...savedFilter, [saveName]: {}};
then update the result with a loop:然后用循环更新结果:
for (const {id, value} of filteredSearchItems) {
savedFilter[saveName][id] = value;
}
Here's an example assuming you want to replace the [saveName]
property if it exists:这是一个示例,假设您要替换
[saveName]
属性(如果存在):
const filteredSearchItems=[{ "id":"das", "value":45 }, { "id":"das3", "value":48 }, { "id":"das4", "value":47 }, { "id":"das5", "value":46 }, ]; let savedFilter = {somethingAlreadyThere: 42}; const saveName = "fooCriteria"; savedFilter = {...savedFilter, [saveName]: {}}; for (const {id, value} of filteredSearchItems) { savedFilter[saveName][id] = value; } console.log(savedFilter);
There are other, more complicated ways ( reduce
, map
and Object.fromEntries
, ...), but they don't have any advantage over the simple, straightfoward loop.还有其他更复杂的方法(
reduce
、 map
和Object.fromEntries
等),但与简单、直接的循环相比,它们没有任何优势。
That said, the map
and Object.fromEntries
version is really concise, if that's your thing:也就是说,
map
和Object.fromEntries
版本非常简洁,如果这是你的事:
// Assumes you want to replace the [saveName] property entirely
const saveName = "fooCriteria";
savedFilter = {
...savedFilter,
[saveName]: Object.fromEntries(filteredSearchItems.map(({id, value}) => [id, value]))
};
const filteredSearchItems=[{ "id":"das", "value":45 }, { "id":"das3", "value":48 }, { "id":"das4", "value":47 }, { "id":"das5", "value":46 }, ]; let savedFilter = {somethingAlreadyThere: 42}; const saveName = "fooCriteria"; savedFilter = { ...savedFilter, [saveName]: Object.fromEntries(filteredSearchItems.map(({id, value}) => [id, value])) }; console.log(savedFilter);
Don't be fooled, though, there's a loop in there (actually two of them, one for map
, the other for fromEntries
).但是,不要被愚弄,那里有一个循环(实际上是其中两个,一个用于
map
,另一个用于fromEntries
)。 :-) :-)
Using ...spread operator you can do it something like this:使用...spread运算符,您可以执行以下操作:
const filteredSearchItems = [{ "id": "das", "value": 45 }, { "id": "das3", "value": 48 }, { "id": "das4", "value": 47 }, { "id": "das5", "value": 46 }, ] let savedFilter = ""; const savefilter = () => { const saveName = "fooCriteria"; let res = {}; filteredSearchItems.forEach(item => { if (!savedFilter) { savedFilter = { [saveName]: { [item.id]: item.value } }; } else savedFilter[saveName] = { ...{ [item.id]: item.value }, ...savedFilter[saveName] } }); }; savefilter(); console.log("savedFilter :", savedFilter.fooCriteria)
const filteredSearchItems=[{
"id":"das",
"value":45
},
{
"id":"das3",
"value":48
},
{
"id":"das4",
"value":47
},
{
"id":"das5",
"value":46
},
]
var a1={};
for(let i=0 ; i<filteredSearchItems.length;i++){
let id1 = filteredSearchItems[i].id;
let id2 = filteredSearchItems[i].value;
a1[id1] = id2;
}
var t2 = {"fooCriteria": a1}
console.log(JSON.stringify(t2));
Output : {"njkcnv":{"das":45,"das3":48,"das4":47,"das5":46}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.