JavaScript/lodash数据转换 [英] JavaScript/lodash data transformation
本文介绍了JavaScript/lodash数据转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var original = {
"8": [{
"temp": {
"a": 1
},
"algo_id": 1
},
{
"temp": {
"a": 2
},
"algo_id": 101
}
],
"13": {
"temp": {
"temp1": [1, 2]
},
"algo_id": 2
}
};
const values = _.values(original);
const temp = _.map(values, (v) => {
if (_.isArray(v)) {
return _.mapValues(_.keyBy(v, 'algo_id'), a => _.pick(a, 'temp'));
}
});
console.log(temp);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
预期:
地图,其中algo_id为键,而temp为值. 像下面这样等等.
map which has algo_id as key and temp as values. like below and so on.
{
"1": {
"temp": {
"a": 1
}
},
"101": {
"temp": {
"a": 2
}
},
"2": {
"temp": {
"temp1": [1, 2]
}
}
}
如何添加对象中非数组的键和值?
How to add key and values which are not array in the object.?
推荐答案
执行此操作的一种方法(不使用lodash)如下:
One way to do this (not using lodash) is the following:
const transform = (original) => Object.values(original)
.flat()
.reduce((all, {algo_id, ...rest}) => ({...all, [algo_id]: rest}), {})
const original ={"13": {"algo_id": 2, "temp": {"temp1": [1, 2]}}, "8": [{"algo_id": 1, "temp": {"a": 1}}, {"algo_id": 101, "temp": {"a": 2}}]}
console.log(transform(original))
但这假定您可以按原样使用algo_id
的同级.您的示例似乎显示了它的进一步处理,我看不出有任何规定.
But this makes the assumption that you can use the sibling of algo_id
as is. Your example seems to show further processing of it that I can't see any rule for.
如果您的目标环境不支持flat
,则可以替换为:
If your target environments don't support flat
, you can replace this:
.flat()
与此:
.reduce((a, b) => a.concat(b), [])
这篇关于JavaScript/lodash数据转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文