1

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?

Nick.

2
  • This new array is smaller in length also or only in terms of attributes? is there a one on one mapping between attributes of both array? Apr 22, 2016 at 12:52
  • Are we talking about arrays or objects?
    – zoom
    Apr 22, 2016 at 12:53

2 Answers 2

1

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

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>');

1
  • I voted up, thanks for the support! This will help me out. Apr 22, 2016 at 13:00
1

Assuming for an array of objects You can use 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)

1
  • Thanks for the support! Apr 22, 2016 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.