-1

I have obj created as shown below

var data_content = [{
    project_name: 'First',
    info: {
      Value1: 'one',
      Value2: 'two'
    }
  },
  {
    project_name: 'Second',
    info: {
      Value1: 'one'
    }
  }
];

I want to delete key/value pairs using the value of key project_name

If I am deleting from a value called first the result should be

data_content = [{
  project_name: 'Second',
  info: {
    Value1: 'one'
  }
}];

Please help me how I can achieve this

mplungjan
  • 169,008
  • 28
  • 173
  • 236
kavya
  • 325
  • 2
  • 10

4 Answers4

2

Use filter function

const filtered_content = data_content.filter(d => d.project_name !== 'First');
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
0

If there is only going to be one item you can use findIndex() and splice()

var data_content=[{project_name:"First",info:{Value1:"one",Value2:"two"}},{project_name:"Second",info:{Value1:"one"}}];

const idx = data_content.findIndex(e => e.project_name==='First');
idx > -1 && data_content.splice(idx,1)

console.log(data_content)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

You can see similar problem on here Remove array element based on object property

data_content = data_content.filter(function( obj ) {
    return obj.project_name !== 'First';
});
koko-js478
  • 1,703
  • 7
  • 17
0

I assume dashboard_info from the second code snippet is practically the same as info from the first snippet

If so you can simply use the delete keyword in a given property of an object to remove it

So var it= obj["key"] then delete it, or simply, in general delete obj["key"]

The thing that makes your case interesting is that it's not just about deleting a known property, it's about deleting, in fact, an entire object, from an array (just thought it would be useful to give the delete intro in case you also why to modify a property of an object)

To delete an element from an array, you use Array.splice(indexToStartAt, numberOfElementsToCutOut)

So in this case, you would want to do data_content.splice(0,1) since you went to start deleting at the 0th index, and you only want to delete one element

The thing is though that I'm guessing you want to make this dynamic, such that you want to delete any element from the array whose property "project_name" equals "First", to do that you can traverse the array with a recursive function


var cur=0

function go(str) {
    var found = data_content.find(x=>x.project_name==str)
    if (found) {
        data_content.splice(data_content.indexOf(found),1)
        if (++cur < data_content.length) 
            go(str)
    }
}
go("First")