如何折叠一个string元素的数组到其string?

承担

{ "foo":[ "baz" ], "bar": { "blarg": [ "blippo" ], "blunder": { "bus": [ { "bigly": [ "bugnuts" ] } ] } }, "blather": [ { "bumpy": [ "bugaloo" ] }, { "blither": { "bother": [ "bingo" ] } } ] } 

什么是最有效的方法(最好使用lodash)转换,所有叶子是一个成员的数组现在包含该成员,而不是数组? 如:

 { "foo": "baz", "bar": { "blarg": "blippo", "blunder": { "bus": { "bigly": "bugnuts" } } }, "blather": [ { "bumpy": "bugaloo" }, { "blither": { "bother": "bingo" } } ] } 

这个物体比我在这里介绍的物体大得多,所以有很多可能的path。

我试着先得到一个path列表,如下所示:

 foo[0] foo bar.blarg[0] bar.blarg bar.blunder.bus[0] bar.blunder.bus bar.blunder bar blather[0].bumpy[0] blather[0].bumpy blather[0] blather[1].blither.bother[0] blather[1].blither.bother blather[1].blither blather[1] blather 

并试图首先在深度和广度上进行突变,但当然,第一种突变有可能使其他path无效。

我想这是一个recursion问题,但解决scheme逃避了我。

这里有一个cloneDeepWith()方法,它也涵盖了包含单个对象的折叠数组。

 var result = _.cloneDeepWith(data, function customizer(value) { if(_.isArray(value) && _.size(value) === 1) { value = value[0]; return _.isObject(value)? _.cloneDeepWith(value, customizer): value; } }); console.log(result); 
 var data = { "foo":[ "baz" ], "bar": { "blarg": [ "blippo" ], "blunder": { "bus": [ { "bigly": [ "bugnuts" ] } ] } }, "blather": [ { "bumpy": [ "bugaloo" ] }, { "blither": { "bother": [ "bingo" ] } } ] }; var result = _.cloneDeepWith(data, function customizer(value) { if(_.isArray(value) && _.size(value) === 1) { return _.isObject(value[0])? _.cloneDeepWith(value[0], customizer): value[0]; } }); console.log(result); 
 body > div { min-height: 100%; top: 0; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> 

cloneDeepWith提供了一种在克隆对象时自定义对象的方法。

 const {cloneDeepWith, isArray} = require('lodash') const flatter = cloneDeepWith(data, value => { if ( isArray(value) && value.length === 1 ) return value[0] }) 

recursionforEach可以让你改变现有的对象(或forIn / forOwn如果需要的话)。

 const {forEach} = require('lodash') function process(obj){ forEach(obj, (val, key)=> { if ( isArray(val) && val.length === 1 ) return obj[key] = val[0] if ( isObject(val) ) process(val) }) }