0

I need to update the data in local db based upon the response from the server but i am getting lot of data from the server which is not needed for local db so i have manually deleted those unwanted values but i would like to do this in a dynamic way. so i have taken the columns name from local db using pragma and i compared the values which i got from the server with the names which i had stored in the array.But i would like to store the key and value in a object.can anyone tell me how to do it?

columns = ['id', 'name', 'category'];
category = {id: 122, name: 'ABD', category: 'Food', created_at: '2014-05-20', is_deleted: 'false'};

I need the result as: var data = {id: 122, name:'ABD', category: 'Food'};

Code:

for (var j = 0; j < columns.length; j++) {
          $log.log('Merged data is', value.category[columns[j]]);
          $log.log('Data is', data);
        }
1
  • Using reduce is good for this type of thing eg. -> columns.reduce((a,v)=>(a[v]=category[v]) && a,{}) ps, if you don't mind using ES6, and you want me to explain how this works, let us know.. Commented Sep 20, 2017 at 12:22

2 Answers 2

2

You can iterate over the array and check if the element is a property in the object. If not then you can delete that property from the object.

for (var j = 0; j < columns.length; j++) {
      if(category[columns[j]] === undefined){
        delete category[columns[j]];
      }
}

Edit:

As asked in comments, if you don't want to delete the properties you can create a new object with the required properties:

var data = {};
for (var j = 0; j < columns.length; j++) {
    data[columns[j]] = category[columns[j]];
}
console.log(data);
Sign up to request clarification or add additional context in comments.

2 Comments

but i don' t want to delete the extra one i need to take values for the columns available in local db.
Hi @Nidhinkumar please check now if it solves your purpose or not and accept the answer if it does.
0

A lodash one-line solution if you like:

var data = _.map(category , _.partialRight(_.pick, ['id', 'name', 'category']));

lodash docs here https://lodash.com/docs/4.17.4

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.