0

First of all, I'm sorry that this might be a duplicate of another question somewhere, but I don't know if my wording was wrong in my searches, but I couldn't find an exact solution to the issue I'm having, so I do apologize in advance if this is a duplicate.

Now the issue.

I have an array of objects, that has various properties. I then have another array of strings, where each string represents the name of a property on the objects from the object array.

I want to create a new array of objects, but where the objects in the array, only have the properties with names from the string array.

I have been messing around with this one for a couple of hours, but haven't really got it to work as intended. I've tried doing some Object.keys stuff, combined with both map and indexOf, but I feel like I'm missing something in my logic, and at this point I'm just not sure what.

So basically I have an array of objects:

data = [
    {
        id: 1,
        name: 'john',
        value: 5
    },
    {
        id: 2,
        name: 'ben',
        value: 10
    },
    {
        id: 3,
        name: 'lisa',
        value: 12
    },
];

And an array of strings: desiredKeys = ['id', 'name'];

And I want to create a new array of objects, where each objects only has the 'id' and 'name' property.

Here's a plunker:

https://next.plnkr.co/edit/nU4Y85j7NFuFQqAx?open=lib%2Fapp.ts

My goal would be to create a new array of objects, but where the objects only have the properties in the 'desiredKeys'array, ie:

[
    {
        id: 1,
        name: 'john'
    },
    {
        id: 2,
        name: 'ben'
    },
    {
        id: 3,
        name: 'lisa'
    },
];

Any tips are welcome, thanks in advance!

4 Answers 4

3

You could map the data array and use Object.fromEntries() like this:

const data=[{id:1,name:"john",value:5},{id:2,name:"ben",value:10},{id:3,name:"lisa",value:12},],
      desiredKeys = ['id', 'name'];

const output = data.map(o => 
  Object.fromEntries( desiredKeys.map(k => [k, o[k]]))
)

console.log(output)

If Object.fromEntries() is not supported, you could reduce the keys to get a subset of each object:

const data=[{id:1,name:"john",value:5},{id:2,name:"ben",value:10},{id:3,name:"lisa",value:12},],
      desiredKeys = ['id', 'name'];

const output = data.map(o => 
 desiredKeys.reduce((a, k) => ({ ...a, [k]: o[k] }), {})
)

console.log(output)

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

1 Comment

Thanks for the tip! I chose your solution as the answer, as I found the reduce approach to be very elegant. Thanks again :)
1

You can use map and forEach. Inside map call back iterate over the desiredKey and get the key and value from corresponding object

let data = [{
    id: 1,
    name: 'john',
    value: 5
  },
  {
    id: 2,
    name: 'ben',
    value: 10
  },
  {
    id: 3,
    name: 'lisa',
    value: 12
  },
];
let desiredKeys = ['id', 'name'];

let newData = data.map(function(item) {
  let newObj = {};
  desiredKeys.forEach(function(elem) {
    newObj[elem] = item[elem]
  })
  return newObj;

});

console.log(newData)

1 Comment

Thanks for the tip! I was headed through something like this myself, allthough you cleared it up for me where I went wrong :) I chose the above answer, since I like the usage of reduce, but thanks for a good suggestion as well!
0

Simple Way with less code

With Vanilla JavaScript you can just use the map operator like this:

const data = [
        {
            id: 1,
            name: 'john',
            value: 5
        },
        {
            id: 2,
            name: 'ben',
            value: 10
        },
        {
            id: 3,
            name: 'lisa',
            value: 12
        },
    ];
    
const newData = data.map(({id, name}) => ({ id, name }));

console.log(newData);

1 Comment

Thanks for the tip! Unfortunately, your solution doesn't take in to consideration that the properties I want should be collected from a string array, but one of the above suggestions did so I picked that as a solution. Still thanks for your suggestion :)
0

First copy the data array. Use this it will just remove the value property from each element.

data.forEach((i)=>  delete i.value )

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.