简体   繁体   中英

Change structure of object in JavaScript

I have some data

arr = {
  'a': ['1', '2', '3'],
  'b': ['2', '3', '4'],
  'c': ['3', '5', '6'],
}

How can I change this to

newArr = {
  '1': ['a'],
  '2': ['a', 'b'],
  '3': ['a', 'b', 'c'],
  '4': ['b'],
  '5': ['c'],
  '6': ['c']
}

Would the most efficient way to do something like this

const newData = {};
Object.keys(oldData).forEach(key => {
  newData[key].forEach(value => {
    if (!newData[value]) {
      newData[value] = [];
    }
    newData[value].push(key);
  });
});

Wouldn't it be quite easy with ES6, maybe using reduce() ?

Just change one line

newData[key].forEach(value => {

to

oldData[key].forEach(value => {

 var oldData = { 'a': ['1', '2', '3'], 'b': ['2', '3', '4'], 'c': ['3', '5', '6'], }; const newData = {}; Object.keys(oldData).forEach(key => { oldData[key].forEach(value => { // ^^^^^^ change to oldData instead of newData if (!newData[value]) { newData[value] = []; } newData[value].push(key); }); }); console.log(newData); 

You can use reduce() and one forEach() like this.

 var arr = { 'a': ['1', '2', '3'], 'b': ['2', '3', '4'], 'c': ['3', '5', '6'], } var result = Object.keys(arr).reduce(function(r, e) { arr[e].forEach(function(a) { if (!r[a]) r[a] = []; r[a].push(e) }) return r; }, {}); console.log(result) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM