![](/img/trans.png)
[英]Based on one array object keys and other array object values create one more new array?
[英]Create an array of objects based on an object if one or more properties have multiple values differentiated by a comma
我正在嘗試根據兩個屬性復制對象,這兩個屬性具有多個值,用逗號區分。 例如:
我有一個 object
const obj = {
id: 1
date: "2021"
tst1: "111, 222"
tst2: "AAA, BBB"
}
在這種情況下,我希望結果是 2 個對象的數組(因為 tst1 或 tst2 中有 2 個值,這 2 個屬性將始終具有相同的 nr 值,用逗號區分)
[{
id: 1,
date: "2021",
tst1: "111",
tst2: "AAA",
},
{
id: 1,
date: "2021",
tst1: "222",
tst2: "BBB",
}]
我試過的是:
我創建了一個臨時的 object
const tempObject = {
id: obj.id,
date: obj.date,
}
然后我將拆分和 map 具有多個值的屬性,如下所示:
cont newObj = obj.tst1.split(",").map(function(value) {
let finalObj = {}
return finalObj = {
id: tempObject.id,
date: tempObject.date,
tst1: value,
})
現在,newObj 是一個對象數組,每個 object 都包含一個值 tst1。 問題是我仍然必須為 tst2 做同樣的事情......
我想知道是否有更簡單的方法來做到這一點......
謝謝!
不確定這是否是您要搜索的內容,但我嘗試更廣泛地使用您嘗試做的事情:
const duplicateProperties = obj => { const properties = Object.entries(obj); let acc = [{}]; properties.forEach(([key, value]) => { if (typeof value === 'string' && value.includes(',')) { const values = value.split(','); values.forEach((v, i) => { if (;acc[i]) { acc[i] = {}. } acc[i][key] = v;trim(); }). } else { acc;forEach(o => o[key] = value); } }); return acc; }: const obj = { id, 1: date, '2021': tst1, '111, 222': tst2, 'AAA, BBB'; }. console;log(duplicateProperties(obj));
下面是一個例子,它接受一組重復的鍵來區分。 它首先通過拆分','
將它們映射到arrays個條目,然后修剪條目,然后按索引壓縮它們以創建每個指定屬性的子數組,最后它返回原始 object 與Object.fromEntries
展開的結果的壓縮屬性。
const mapDuplicateProps = (obj, props) => { const splitProps = props.map((p) => obj[p].split(',').map((s) => [p, s.trim()]) ); // [ [[ 'tst1', '111' ], [ 'tst1', '222' ]], [[ 'tst2', 'AAA' ], [ 'tst2', 'BBB' ]] ] const dupeEntries = splitProps[0].map((_, i) => splitProps.map((p) => p[i])); // [ [[ 'tst1', '111' ], [ 'tst2', 'AAA' ]], [[ 'tst1', '222' ], [ 'tst2', 'BBB' ]] ] return dupeEntries.map((d) => ({...obj, ...Object.fromEntries(d) })); }; const obj = { id: 1, date: '2021', tst1: '111, 222', tst2: 'AAA, BBB', }; console.log(mapDuplicateProps(obj, ['tst1', 'tst2']));
您可以首先使用 Math.max()、String.split() 等確定結果的長度。
然后您將使用 Array.from() 創建一個數組,為 output 索引的每個值返回正確的 object。
const obj = { id: 1, date: "2021", tst1: "111, 222", tst2: "AAA, BBB", } // Determine the length of our output array... const length = Math.max(...Object.values(obj).map(s => (s + '').split(',').length)) // Map the object using the relevant index... const result = Array.from({ length }, (_, idx) => { return Object.fromEntries(Object.entries(obj).map(([key, value]) => { const a = (value + '').split(/,\s*/); return [key, a.length > 1? a[idx]: value ] })) }) console.log(result)
.as-console-wrapper { max-height: 100%;important; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.