1

I have a case like i want to add key, value pair to an object in angular 5 typescript. that should look like below

Expected output:

{key1 : val1, key2 : val2, key3 : val3}

Actual output:

[{kek1 : val1}, {key2 :  val2}, {key3 : val3}]

Actual code tried: //forgot abot the syntax error if any

for(int i=0; i<3; i++){
this.rowData.push({
      key+i : val+1
    });
}

When i add the set of values in string and tried to add it to array, it comes like below

let pairs : string = '';
 pairs = pairs.concat('key1',':','val1','',',');
this.rowData.push({
      {"pairs":"key1:val1,key2:val2"}
    });

in the above code i am getting extra word "pairs" and double quotes to values.

1
  • You can consider using array#reduce. Or use an object initially and populate key and value, instead of using an array. Commented Apr 16, 2018 at 14:07

2 Answers 2

1

Try with this

rowData = {};

for(const i < 0; i < 3; i++) {
  rowData['key' + (i + 1)] = 'val' + (i + 1);
}
Sign up to request clarification or add additional context in comments.

4 Comments

This will fail if the keys have different name pattern
@ToshkataTonev this can't fail since you're creating keys.
Sorry, i had different expectations result in my head.
@ToshkataTonev no problem, just making it clear for other people
0

First of this has nothing todo with either array manipulation (since you expect an object) nor Angular 5 or typescript. This is plain Vanilla JS.

var rowData = {};
for(int i=0; i<3; i++){
    rowData[key+i] = val+1;
}

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.