[英]Merge array items and object values by common key/index
我有一個像這樣的 arrays 數組:
let a = [
['A', 'B'], // 1 in the object
['C'], // 2 in the object
];
我有一個像這樣的對象的 object:
let b = {
5:{
1: "i was send to earth. i was send to her.",
2: "to mars",
3: { reference: "to moon.", expectSt: "to mars. i love it." },
},
};
如您所見,object 中有兩種模式。 像 1 和 2 的模式和像 3 的模式。
我只想將 1 中的句子添加到let a
內的第一個數組中,並將 2 中的句子添加到let a
a 內的第二個數組中,依此類推......
如果模式像 3 那么我只想添加expectSt
句子並忽略reference
結果應該是這樣的:
let a = [
['A', 'B', 'i was send to earth', 'i was send to her'], // 1 in the object
['C', 'to mars'], // 2 in the object
['to mars', 'i love it'], // there is a 3 i the object so we added this
];
我已經嘗試了很多,但我認為我需要幫助解決這個問題。
這么簡單的事情對你有用嗎?
let a = [['A','B'],['C'],], b = {5:{1:"i was send to earth. i was send to her.",2:"to mars",3:{reference:"to moon.",expectSt:"to mars. i love it."},},} Object.values(b[5]).forEach((value,key) => a[key] = [...(a[key]||[]), ...(value.expectSt || value).toLowerCase().replace(/\.$/,'').split('. ') ] ) console.log(a)
.as-console-wrapper{min-height:100%;}
let a = [
['A', 'B'], // 1 in the object
['C'], // 2 in the object
];
let b = {
5:{
1: "i was send to earth. i was send to her.",
2: "to mars",
3: { reference: "to moon.", expectSt: "to mars. i love it." },
},
};
Object.values(b).forEach(element => {
Object.keys(element).forEach(e => {
console.log(element[e]);
if(e === '1') a[0].push(...element[e].split('.').filter(a => a !== '').map(a => a.trim()));
else if(e === '2') a[1].push(...element[e].split('.').filter(a => a !== '').map(a => a.trim()));
else if(e === '3') {
if(a.length < 3) a.push([]);
a[2].push(...element[e].expectSt.split('.').filter(a => a !== '').map(a => a.trim()))
}
})
});
console.log(a);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.