Javascript基于键合并两个对象 [英] Javascript merge two objects based on key

查看:83
本文介绍了Javascript基于键合并两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些形状如下的物体.

I have some objects in the shape of below.

[{
    product: 'ABC',
    productId: 'AB123',
    batch: 'BA1',
    price: '12'
}, {
    product: 'ABC',
    productId: 'AB123',
    batch: 'BA2',
    price: '15'
}, {
    product: 'XYZ',
    productId: 'AB124',
    batch: 'XY1',
    price: '124'
}]

如果要对键对(productproductId)进行数学计算,我想将对象合并到数组中的单个对象中,格式如下.

I want to merge objects into one single object in the array if key pair (product, and productId) are mathced, in the below format.

[{
    product: 'ABC',
    productId: 'AB123',
    batch: ['BA1', 'BA2'],
    price: ['12', '15']
}, {
    product: 'XYZ',
    productId: 'AB124',
    batch: 'XY1',
    price: '124'
}]

如何在lodash或纯JavaScript中做到这一点.

How can I do it in lodash or in pure javascript.

推荐答案

此提议不会更改给定的数据.

This proposal does not alter the given data.

它创建新对象,首先仅包含单个数据,然后如果应该对更多数据进行分组,它将对batchprice使用数组.

It creates new objects, first with just single data, later if more data should be grouped, it uses an array for batch and price.

var data = [{ product: 'ABC', productId: 'AB123', batch: 'BA1', price: '12' }, { product: 'ABC', productId: 'AB123', batch: 'BA2', price: '15' }, { product: 'XYZ', productId: 'AB124', batch: 'XY1', price: '124'}],
    merged = [];

data.forEach(function (a) {
    if (!this[a.productId]) {
        this[a.productId] =  { product: a.product, productId: a.productId, batch: a.batch, price: a.price };
        merged.push(this[a.productId]);
        return;
    }
    if (!Array.isArray(this[a.productId].batch)) {
        this[a.productId].batch = [this[a.productId].batch];
    }
    if (!Array.isArray(this[a.productId].price)) {
        this[a.productId].price = [this[a.productId].price];
    }
    this[a.productId].batch.push(a.batch);
    this[a.productId].price.push(a.price);
}, Object.create(null));

console.log(merged);

这篇关于Javascript基于键合并两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆