Nick Mulder Nick Mulder - 6 months ago 6
Javascript Question

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

Today I'm busy with storing data from a larger Array to a smaller Array, but with different key attributes. The smaller Array contains also less keys, so I have to split or remove keys from the larger one.

This is the structure of the two Arrays:

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

As you can notice, some keys are (almost) ready to insert into the smaller Array, but I still need to split the large Array. Or is it possible to select the keys you want and then insert it into the smaller Array? Anyway, can someone help me out with this?



Maybe with a nested loop, one for the array and one for the wanted properties.

function getParts(array, parts) {
    return (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>');