Untitled
plain_text
a month ago
1.8 kB
2
Indexable
Never
// description: key is a have dictionary is b const arr =[{ A: 'B'},{B:'C'},{C:'D'},{D:'E'},{E:'F'}] //with addition case {F:'a'} => Infinity loop , //if db have this case will case error /*expect: A -F B-F C-F D-F E-F */ //turn into 1 object have key is key and value // const keyValue = arr.reduce(function(result, item) { var key = Object.keys(item)[0]; result[key] = item[key]; return result; }, {}); //array key to loop const mainKey = arr.flatMap(Object.keys) const result ={} let count =0; for (let i=0; i< mainKey.length;i++) { count +=1 let middleDictionary =[] let key = mainKey[i] let dictionary = keyValue[key] //exist loop before => have final key- value in dictionary //exp: case f:b => b have final => get from b //reduce some redundant loop if(result[dictionary]) {result[key] = result[dictionary];continue;} //if not above case => loop key first time if (!result[key]) result[key] =dictionary; while(keyValue[dictionary]) { dictionary = keyValue[dictionary] count+=1 middleDictionary.push(dictionary) } //save key that also distionary had been gone through //then update when final dictionary if(middleDictionary.length) { for(let j=0; j< middleDictionary.length; j++) { //for case final dictionary - final dictionary if(keyValue[middleDictionary[j]]) result[middleDictionary[j]] = dictionary } } result[key] =dictionary } const arrRes = Object.keys(result).map(i=> ({key :i, dictionary : result[i]})) console.log('input key-dictionary is ', arr) console.log('array key is',mainKey) console.log('object have only key-value is', keyValue) console.log('result is',result) console.log('count is ', count) console.log('final arr result', arrRes)