我有一个像这样的对象数组:
[
{
x_issue: 'Cost, Taste, Other',
y_a_issue: 'Spillover'
},
{
x_issue: 'Cost, Taste',
y_a_issue: 'Spillover'
},
{
x_issue: 'Taste, Other',
y_a_issue: 'Packaging'
}
]
我需要结果数组如下:
{
"x": {
"response": {
"Cost": 2,
"Taste": 3,
"Other": 2
}
},
"y_a": {
"response": {
"Spillover": 2,
"Packaging": 1
}
}
}
另外,我有一个参数数组
['x', 'y_a', 'z']
这里可能有更多参数,如x,y。最后一个字符串问题在每个参数中保持不变。它按事件分组 成本已经输入两次,Taste进入了三次。
我怎样才能在javascript中执行此操作?我正在使用lodash。
这就是我的尝试:
这里data
是一个对象数组,它是一个mongodb对象。参数是我上面提到的参数数组。
let obj = {};
_.forEach(data, (v, k) => {
obj.parameters = [];
_.forIn(v.toJSON(), (val, key) => {
// let count = 0;
var bucket = _.find(parameters, k => _.startsWith(key, k));
if (bucket) {
if (key === `${bucket}_issue`) {
obj[bucket] = obj[bucket] || {};
obj[bucket]["response"] = obj[bucket]["response"] || {};
obj[bucket]["response"]["all"] = obj[bucket]["response"]["all"] || [];
obj[bucket]["response"]["all"].push(_.words(val));
}
}
});
});
答案 0 :(得分:1)
在纯JavaScript中,你可以使用forEach()
循环
var data = [{
x_issue: 'Cost, Taste, Other',
y_a_issue: 'Spillover'
}, {
x_issue: 'Cost, Taste',
y_a_issue: 'Spillover'
}, {
x_issue: 'Taste, Other',
y_a_issue: 'Packaging'
}]
var o = {}
data.forEach(function(e) {
Object.keys(e).forEach(function(k) {
var p = e[k].split(', ');
var re = /\_(?:.(?!\_))+$/
var key = k.split(re)[0];
if (!o[key]) o[key] = {response: {}};
p.forEach(function(a) {
o[key].response[a] = (o[key].response[a] || 0) + 1;
})
})
})
document.body.innerHTML = '<pre>' + JSON.stringify(o, 0, 4) + '</pre>';
&#13;
答案 1 :(得分:1)
您可以使用_.mergeWith()
和自定义程序函数来实现所需的合并,然后使用_.transform()
循环结果以从每个键中删除`_issue:
var arr = [{
x_issue: 'Cost, Taste, Other',
y_a_issue: 'Spillover'
}, {
x_issue: 'Cost, Taste',
y_a_issue: 'Spillover'
}, {
x_issue: 'Taste, Other',
y_a_issue: 'Packaging'
}];
/** Create the mergeWithResponse method **/
var mergeWithResponse = _.partialRight(_.mergeWith, function(ov, sv) {
var oValue = ov ? ov : { // if the original value is undefined initialize it with a response property
response: {}
};
return sv.split(',').reduce(function(final, word) { // split the words of the source value and iterate them
var w = word.trim(); // remove space before and after the words
final.response[w] = (final.response[w] || 0) + 1; // add the word to the response and / or increment the counter
return final; // return the final value with the response object
}, oValue);
});
var result = _(mergeWithResponse.apply(_, [{}].concat(arr))) // add an empty object to the beginning of the array, and apply the new array as paramaters for mergeWithResponse
.transform(function(result, value, key) { // remove the "_issue" string an from each key, and create an object with the new keys
var k = key.replace('_issue', '');
result[k] = value;
});
console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.2/lodash.min.js"></script>
&#13;