不可变 JS - 将地图集合转换为列表

Immutable JS - converting a collection of Maps to a List

我正在处理的项目中有以下结构(使用不可变的 JS):

data :[{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
       {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}]

对象通过 fromJS() 转换为不可变 JS。

我需要一个具有以下结构的新对象:

data :[{name: 'john', surname: 'smith', children: ['sam','ben']},
       {name: 'jane', surname: 'jones', children: ['tim','amy']}]

非常感谢任何指点。

类似的东西应该可以工作

data.map(d => {d.name, d.surname, children: d.children.map(child => child.name)});

我会使用 map 和 reduce:

const data = [{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
       {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}];
       
var result = data.map(person => {
  return { name: person.name, 
           surname: person.surname, 
           children: person.children.reduce((acc, c) => {acc.push(c.name); return acc;}, []) }});
 
  console.log(result)

Christian 的纯 JS 答案并不完全适用于 immutable.js 对象,因此这里有一些方法可以使用 immutable.js 的集合 API。

还有更多选择(例如reduce),欢迎查看the docs;方法描述通常带有示例。

const raw = [{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
       {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}];

const data = Immutable.fromJS(raw);

function run(name, operation) {
  let result;
  console.time(name);
  for(let i=0; i < 50000; i++){
    result = operation();
  }
  console.timeEnd(name);
  console.log(result1.toJS());
}


run('simple', () => {
  // simply updating objects inside a mapping
  result1 = data.map(
    person => person.update('children',
      kidObjs => kidObjs.map(
        kid => kid.get('name')
      )
    )
  );
});


run('withMutations and setIn', () => {
  // using withMutations and setIn
  result2 = data.withMutations(list => {
    list.forEach((val, idx) => {
      list.setIn(
        [idx, 'children'],
        val.get('children').map(kid => kid.get('name'))
      )
    });
  });
});

run('withMutations and update', () => {
  // slightly faster by using withMutations set/update
  result2 = data.withMutations(list => {
    list.forEach((val, idx) => {
      list.set(idx, val.update('children', kids => kids.map(kid => kid.get('name'))))
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.14/immutable.min.js"></script>