[英]Add complex array of objects into another object
我有一個看起來像這樣的源 object obj
和一個數組input
const obj = {
name: "xyz",
filter: {
and: [
{
or: [
{
and: []
}
]
}
]
}
};
const input = ["test1\name1", "test2\name2"]
我需要推動由\
分割input
后形成的對象。 拆分后,使用字符串的左側我需要像這樣形成 object
{ type: "type1", value: whatever the left hand value}
右側值相同
{ type: "type2", value: whatever the right hand value}
並且這些對象應該被推到最里面and
在源 object 中。
預期 output
{
name: "xyz",
filter: {
and: [
{
or: [
{
and: [
{ type: "type1", value: "test1" },
{ type: "type2", value: "name1" },
{ type: "type1", value: "test2" },
{ type: "type2", value: "name2" }
]
}
]
}
]
}
}
我試過的代碼
function processResult(input) {
return {
name: "xyz",
filter: {
and: [
{
or: [
{
and: getUpdatedValues(input)
}
]
}
]
}
};
}
// I need the getUpdateValues to be processing the each item from the input array and then sending the two objects back after splitting
function getUpdatedValues(input){
const updated = input.map(item => {
const spilt = item.split("\\");
});
}
假設輸入數組將包含轉義字符並且可能如下所示: ["test1\\name1", "test2\\name2"]
,下面介紹的是實現所需目標的一種可能方法。
代碼片段
const transformMyArr = (myArr) => ( myArr.flatMap( s => { const [leftie, rightie] = s.split('\\'); return ([{ type: 'type1', value: leftie }, { type: 'type2', value: rightie }]); } ) ); /* code explanation // method to transform the array to required format const transformMyArr = (myArr) => ( myArr.flatMap( // iterate over the array and remove nested-array in result s => { // manipulate each array element // "split" using "\\" and store the left-side as "type" // and the rest as "value" const [type, value] = s.split('\\'); // explicit return of an array with two objects per array elt return ([{ type: 'type1', value: leftie }, { type: 'type2', value: rightie }]); } ) // implicit return from the "transformMyArr" method ); */ let myInputArr = ["test1\\name1", "test2\\name2"]; const myObj = { name: "test", filter: { and: [{ or: [{ and: [...transformMyArr(myInputArr) ] }] }] } }; console.log('updated obj:\n', myObj);
.as-console-wrapper { max-height: 100%;important: top: 0 }
解釋
添加到上述代碼段的內聯注釋。
一種方法。 這很棘手,因為輸入結構與 output 非常不同,並且除了數組元素 position 之外沒有“type1”/“type2”的引用。
const input = ["test1\\name1", "test2\\name2"]; function processResult(input) { return { name: "xyz", filter: { and: [ { or: [ { and: getUpdatedValues(input) } ] } ] } }; } function getUpdatedValues(input){ return input.flatMap((item, i) => item.split("\\").map(val => ({[`type${i + 1}`]: val }))); } console.log(processResult(input));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.