[英]How to split an array of strings & return a single object with key/value pairs
[英]mapping an array of strings to an array of numbers based on key value pairs of another object
我正在嘗試 map 一個字符串數組
arrString = [
["A", "B"],
["C", "D"],
["E", "F"],
["D", "A"],
["F", "C"],
["G", "E"]
]
基於 object 鍵值:
map = {
'0': 'A',
'1': 'B',
'2': 'C',
'3': 'D',
'4': 'E',
'5': 'F',
'6': 'G'
}
成一個數字數組
arrNum = [
["0", "1"],
["2", "3"],
["4", "5"],
["3", "0"],
["5", "2"],
["6", "4"]
]
這就是我所做的:
const map = {}
const arrNum = Array.from(new Array(arrString.length), () => new Array(arrString[0].length).fill([]));
for(let i = 0; i < arr2.length; i++){
map[i] = arr2[i]
}
for(let ele in arrString){
// I can't figure out how to if the obbject value is equal to ele push it's key to arrNum
if (Object.values(map).includes(ele))
}
如您所見,我正在嘗試遍歷 arrString,然后如果任何元素等於 map 中的值,我想將其鍵添加到 arrNum。
所以有人知道該怎么做,這樣我就可以得到arrNum
了嗎?
const arrString = [ ["A", "B"], ["C", "D"], ["E", "F"], ["D", "A"], ["F", "C"], ["G", "E"] ] map = { '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G' } const arrNum = arrString.map(as => as.map(a => { for(const k in map){ if (map[k] === a) return k; } })); console.log(arrNum);
您可以使用:
const arrString = [ ["A", "B"], ["C", "D"], ["E", "F"], ["D", "A"], ["F", "C"], ["G", "E"] ]; map = { '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G' }; const keys = Object.keys(map); const arrNum = arrString.map(item => item.map(value => keys.find(key => map[key] === value))); console.log(arrNum);
先把map倒過來,然后用它來匹配字母。
const arrString = [ ["A", "B"], ["C", "D"], ["E", "F"], ["D", "A"], ["F", "C"], ["G", "E"] ] const map = { '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G' } const invertedMap = Object.fromEntries(Object.entries(map).map(([a,b])=>[b,a])) console.log('Inverted Map:',invertedMap) const output = arrString.map(inner => inner.map(char => invertedMap[char])) console.log('Result:',output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.