Hyperlink
我想要json数组,例如唯一的this数组,并在其中创建价格数组,如quoteId匹配的
输出
MyJsonArray =
[{quoteId: "MqWmJkUzcP", price: 211, userName: "Test"},{quoteId: "OqgFavcIiR", price: 230, userName: "Aglowid"},{quoteId: "MqWmJkUzcP", price: 120},
{quoteId: "IFeiWnxMfq", price: 146, userName: "Test-2"},
{quoteId: "pVL0CgIxaN", price: 155, userName: "Test-2"}]
很抱歉键入和语法错误,因为我从手机上问了这个问题
答案 0 :(得分:2)
这是您使用纯JavaScript(es6)的方式
const mergePrice = data => data.reduce((result, val) => {
const { quoteId, price, userName } = val;
let obj = result.find(o => o.quoteId === quoteId);
if (!obj) {
obj = { quoteId, userName, price: [] };
result.push(obj);
}
obj.price.push(price);
return result;
}, []);
const merged = mergePrice([{quoteId: "MqWmJkUzcP", price: 211, userName: "Test"},{quoteId: "OqgFavcIiR", price: 230, userName: "Aglowid"},{quoteId: "MqWmJkUzcP", price: 120},
{quoteId: "IFeiWnxMfq", price: 146, userName: "Test-2"},
{quoteId: "pVL0CgIxaN", price: 155, userName: "Test-2"}]);
console.log(merged);