user2061886 user2061886 - 11 days ago 4
Javascript Question

setting javascript variable to certain object attributes

I have a fairly basic javascript question that I can't seem to figure out. Lets say I have a data object like this:

var data = [
{
key: 1,
attr2: "2",
attr3: "3",
attr4: "4",
attr5: "5"
};
{
key: 2,
attr2: "10",
attr3: "3a",
attr4: "ad",
attr5: "5asdf"
};
{
key: 3,
attr2: "a",
attr3: "b",
attr4: "c",
attr5: "d"
};


and I want to create another object with just attr1 and attr2, do I do it like this?

var data2 = data[attr1, attr2]


tried it this way but I get
attr1 is undefined
.

Answer

You could use an array with the keys and map the new objects with the wanted keys.

While you have no key attr1, you get undefined.

var data = [{ key: 1, attr2: 2, attr3: 3, attr4: 4, attr5: 5 }, { key: 2, attr2: 10, attr3: '3a', attr4: 'ad', attr5: '5asdf' }, { key: 3, attr2: 'a', attr3: 'b', attr4: 'c', attr5: 'd' }],
    keys = ['attr1', 'attr2'],
    result = data.map(function (a) {
        var o = {};
        keys.forEach(function (k) {
            o[k] = a[k];
        });
        return o;
    });

console.log(result);

Bonus: Short version in ES6 with Array#reduce and Object.asign

var data = [{ key: 1, attr2: 2, attr3: 3, attr4: 4, attr5: 5 }, { key: 2, attr2: 10, attr3: '3a', attr4: 'ad', attr5: '5asdf' }, { key: 3, attr2: 'a', attr3: 'b', attr4: 'c', attr5: 'd' }],
    keys = ['attr1', 'attr2'],
    result = data.map(o => keys.reduce((r, k) => Object.assign(r, { [k]: o[k] }), {}));

console.log(result);

Comments