0

I have an object in two other objects named formKeyValues and form

formKeyValues

enter image description here

form

enter image description here

I want to push only the keys and values from formKeyValues in a new array parameter - keys are in form.formKeys -

I tried this but it's not working.

this.formKeyValues=this.selectedTimeLine.formKeyValues;
this.parameter=[];
this.formKeyValues.forEach((para)=>{
  if(para.key==this.selectedTimeLine.form.formKeys){
    this.parameter.push('d[/data/'+this.selectedTimeLine.form.formId+'/'+para.key+']='+para.value);
  }
});
Alexis
  • 1,685
  • 1
  • 12
  • 30
  • 1
    https://stackoverflow.com/a/1885569/9868549 this is what you are looking for – Quentin Grisel Jul 22 '20 at 12:17
  • @QuentinGrisel but how i can push them in a variable? –  Jul 22 '20 at 12:20
  • @QuentinGrisel How can i push it in array? can you write it in answer section? –  Jul 22 '20 at 12:22
  • `this.parameter = this.selectedTimeLine.formKeyValues.filter(keyValue => this.selectedTimeLine.form.includes(keyValue.key));` – ruth Jul 22 '20 at 12:22
  • @MichaelD but same question. how can i push all those keys and values in this.parameter ? –  Jul 22 '20 at 12:25
  • @aashu1807: You don't have to manually push it. The array returned from the `filter` operation is _assigned_ to the `this.parameter` variable. – ruth Jul 22 '20 at 12:28
  • @MichaelD as you can see i need this.parameter in some proper format. That's why i am asking –  Jul 22 '20 at 12:30
  • @aashu1807: Now I get what you mean. For that you could use array `map` function on the array returned by the `filter`. I've posted an answer. – ruth Jul 22 '20 at 12:35
  • @aashu1807: please find the run able my answer with your expected format. – Vivek Jain Jul 22 '20 at 12:36

2 Answers2

1

Please find the below solution. I have given the js solution so it can be run able here. You can convert this to angular by replacing var to const.

var formKeyValues = [{
    key: 'key 1',
    value: 1
  },
  {
    key: 'key 2',
    value: 2
  },
  {
    key: 'key 3',
    value: 3
  },
  {
    key: 'key 4',
    value: 4
  },
  {
    key: 'key 5',
    value: 5
  },
];

var form = {
  formId: 1,
  formKeys: ['key 2', 'key 4', 'key 5']
};

var parameters = this.formKeyValues.filter(x => this.form.formKeys.indexOf(x.key) > -1).map(para => 'd[/data/'+this.form.formId+'/'+para.key+']='+para.value);
console.log(this.parameters);
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
1

You could use includes to check if an element is contained in an array, filter to produce an array based on the previous condition, and map to convert the resulting array to your desired format.

Try the following

this.parameter = this.selectedTimeLine.formKeyValues
  .filter(keyValue => this.selectedTimeLine.form.formKeys.includes(keyValue.key))
  .map(keyValue => 'd[/data/'+this.selectedTimeLine.form.formId+'/'+keyValue.key+']='+keyValue.value);
ruth
  • 29,535
  • 4
  • 30
  • 57