(JavaScript) 将数据从较大的数组存储到具有其他关键属性的较小数组

(JavaScript) Store data from larger Array to a smaller Array with other key attributes

今天我忙于将数据从一个较大的数组存储到一个较小的数组,但具有不同的关键属性。较小的数组包含的键也较少,因此我必须从较大的数组中拆分或删除键。

这是两个数组的结构:

Array one (larger one): brand:value, category:value, id:value, name:value, price:value, quantity:value, variant:value

Array two (smaller one): item:value, quantity:value, price:value, unique_id:value

如您所见,一些键(几乎)已准备好插入较小的数组,但我仍然需要拆分大数组。或者是否可以 select 你想要的键,然后将它插入到较小的数组中?不管怎样,有人可以帮我解决这个问题吗?

尼克.

假设对象数组您可以使用Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in this array.

var kvArray = [{
  key: 1,
  value: 10
}, {
  key: 2,
  value: 20
}, {
  key: 3,
  value: 30
}];
var reformattedArray = kvArray.map(function(obj) {
  return {
    "NewProperty": obj.key
  };
});

console.log(reformattedArray)

也许有一个嵌套循环,一个用于数组,一个用于所需的属性。

function getParts(array, parts) {
    return array.map(function (a) {
        var temp = {};
        parts.forEach(function (k) {
            temp[k] = a[k];
        });
        return temp;
    });
}

var array = [{ brand: 'abc', category: 't1', id: 101, name: 'aaa', price: 30, quantity: 10, variant: 'q' }, { brand: 'abc', category: 't1', id: 102, name: 'bbb', price: 28, quantity: 20, variant: 'q' }, { brand: 'def', category: 't1', id: 103, name: 'ccc', price: 40, quantity: 30, variant: '' }, { brand: 'def', category: 't2', id: 104, name: 'ddd', price: 90, quantity: 40, variant: '' }, { brand: 'ghi', category: 't2', id: 105, name: 'eee', price: 12, quantity: 50, variant: 'q' }, { brand: 'ghi', category: 't2', id: 105, name: 'fff', price: 1, quantity: 60, variant: 'q' }];

document.write('<pre>' + JSON.stringify(getParts(array, ['quantity', 'price', 'id']), 0, 4) + '</pre>');