11

I have an array of objects with the same properties. Each object has around a hundred properties. I want to keep only a handful of them in a new array:

const dummyArray = [
    { "att1": "something", "att2": "something", /* … */, "att100": "something" },
    { "att1": "something", "att2": "something", /* … */, "att100": "something" },
    // …
  ];

How can I filter, map, reduce the array, or use some other method to extract the desired keys?

const newDummArray = dummyArray.map(function(item) { 
    delete item.att1; 
    delete item.att3; 
    delete item.att15;
    // Long list …

    return item; 
  });

How can I keep only att20, att30, att70, att80 for each object and delete the rest?

5 Answers 5

22

Use object destructuring to get the properties, and generate a new object using shorthand property names:

const dummyArray = [{ "att20": "att20", "att30": "att30", "att70": "att70", "att80": "att80"}, { "att20": "att20", "att30": "att30", "att70": "att70", "att80": "att80"}];

const result = dummyArray.map(({ att20, att30, att70, att80 }) => ({
  att20, 
  att30, 
  att70, 
  att80
}));

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

8

map creates a new array, so there is no need to delete any thing, instead create an array of interesting keys and return it

var dummyArray = [{
  "att1": "something",
  "att2": "something",
  "att20": "something",
  "att100": "something"
}, {
  "att1": "something",
  "att2": "something",
  "att20": "something",

  "att100": "something"
}];

let x = dummyArray.map((item) => {
  return {
    attr20: item.att20
  }

})

console.log(x)

Comments

8

store the props you want to keep in an array then for each object transfer wanted props to a new object.

var dummyArray = [{ "att1": "something", "att2": "something", "att100": "something"}, { "att1": "something", "att2": "something", "att100": "something"}];

var propsToKeep = ["att1", "att100"];

var result = dummyArray.map(item => {
  const obj = {};
  for (const prop of propsToKeep) {
    obj[prop] = item[prop];
  }
  return obj;
})

console.log(result)

2 Comments

This is fine for a general purpose function, but inefficient when the list of keys is known apriori.
@Alnitak well yeah, but i.e. in ori-dori and brk solutions there's code duplication (key names are repeated). I think code duplication (and any premature optimization mess) is worse than a bit slower but more flexible code
6

I have find easiest way to do this JSON.stringify()

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

    const odata = [
      { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55 },
      { "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67 }
    ];
    const outdata=JSON.stringify(odata,['id','type']);
    console.log(outdata);

3 Comments

Syntax similar to Lodash _.pick() method
that's even more simple and easiest to apply!! tnx
Accept the answer, if this is work for you. @SajjadHossainSagor
2

Here a function that take an object, and extract only the properties that you want. Which you passe through an array as a second parameter.

Advantage: more straight forward and cleaner. Specially when you need to extract from just one object.

If you have a list of object. Map through the list and extract in every iteration.

function objectExtract(obj, properties) {
    return properties.reduce((result, prop) => {
        if (obj.hasOwnProperty(prop)) {
            result[prop] = obj[prop];
        }
        return result;
    }, {});
}

Read about reduce here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce .

use:

(a real example with redux)

store.dispatch(
            setRooms({ 
                ...roomsState,
                list: rooms.reduce((list, room) => {
                    list[room.id] = objectExtract(room, ['name', 'description', 'createdAt', 'updatedAt']);
                    return list;
                }, {})
            })
        )

(On the example of the question)

var dataSourceArray = [{
  "att1": "something",
  "att2": "something",
  "att20": "something",
  "att100": "something"
}, {
  "att1": "something",
  "att2": "something",
  "att20": "something",

  "att100": "something"
}];

let x = dataSourceArray.map((item) => {
  return objectExtrac(item, ['att100', 'att2']);
});

1 Comment

Somehow the spread operator ... in other answers is getting me troubles. The genuine function objectExtract works perfectly for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.