How do I delete a key according to the value of an object?

Asked 2 years ago, Updated 2 years ago, 385 views

If there is an array similar to the following,

containments=[
  { 'id' : 1, 'category' : -1, 'question' : -1, 'answer' : -1} ,
  { 'id' : 2, 'category' : -1, 'question' : 0, 'answer' : -1} ,
  { 'id': 3, 'category': -1, 'question': -1, 'answer':3},
  { 'id' : 4, 'category' : -1, 'question' : -1, 'answer' : -1} ,
]

If you want to delete a key whose value is less than 0 for each object stored in this array, that is,

containments=[
  { 'id':1} ,
  { 'id' : 2, 'question' : 0},
  { 'id' : 3, 'answer' : 3},
  { 'id':4},
]

If you want to get the above results, what kind of method can you think of?
You will now be able to use lodash as your library.

javascript array

2022-09-30 21:54

2 Answers

I have already received an answer to your comment, so I will write down a pattern that does not use lodash.

containments=[
  { id:1, category:-1, question:-1, answer:-1},
  { id:2, category:-1, question:0, answer:-1},
  { id:3, category:-1, question:-1, answer:3},
  { id:4, category:-1, question:-1, answer:-1},
];

/**
 * when written in a straightforwardly written
 */
const result1 = items.map(item=>
  Object.entries (item)
    .filter([,value])=>value>=0)
    .reduce((all, [key, value])=>({...all, [key]: value}, {},
);

/**
 * If this process is made into a function so that filtering processing can be done arbitrarily,
 */
function pickBy(list, filterFunction){
  return list.map(obj)=>
    Object.entries(obj)
      .filter([key,value])=>filterFunction(key,value))
      .reduce((all, [key, value])=>({...all, [key]: value}, {},
  );
}

const result2=pickBy(items,(_,value)=>value>=0);

console.log("====result1====");
console.log(JSON.stringify(result1, null,2));
console.log("====result2====");
console.log (JSON.stringify(result2, null, 2)); 


2022-09-30 21:54

From the expression "Delete Key", we assumed that we were expecting destructive action.
You can delete properties using the delete operator.

'use strict';
conditions = [
  { 'id' : 1, 'category' : -1, 'question' : -1, 'answer' : -1} ,
  { 'id' : 2, 'category' : -1, 'question' : 0, 'answer' : -1} ,
  { 'id': 3, 'category': -1, 'question': -1, 'answer':3},
  { 'id' : 4, 'category' : -1, 'question' : -1, 'answer' : -1} ,
];

for (let item of items) {
  for (let[key, value] of Object.entries(item)) {
    if(value<0){
      delete item [key];
    }
  }
}

console.log(JSON.stringify(items); // [{"id":1}, {"id":2, "question":0}, {"id":3, "answer":3}, {"id":4}]

Dear Re:hitenMITSURUGIstyle,


2022-09-30 21:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.