1

I have values like this

var npi = {
            code1: 'sm1',
            code2: 'sm8',
            code3: 'sm9',
            code4: ''
          }

I want to push first 3 items into an array

var arr = [];
for (var i =0;i< 3;i++) {
  arr.push(npi.code+''+i);
}

It says error npi.code is undefined since it is not considering npi.code1 instead npi.code.

Here i think its concat problem.Can anyone please suggest me help.Thanks.

4
  • There is no npi.code0 Your i starts from 0 Commented Jul 11, 2017 at 10:31
  • 1
    Use npi['code'+i] Commented Jul 11, 2017 at 10:32
  • Consider using Object.keys. Commented Jul 11, 2017 at 10:34
  • Any reason why only the first 3? Could it be you only want the none empty onces? Commented Jul 11, 2017 at 10:40

5 Answers 5

3

npi.code+''+i won't work because there is no such key code+''+i . Instead you could access the key in this way npi['code'+i] (like accessing array using index).

Also in your code, the i start with 0 and code0 is undefined. So, i should start with 1

Try this one

var arr = [];
for (var i = 1;i <= 3;i++) {
  arr.push(npi['code'+i]);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Would need to start at 1, also good idea to explain what is happening + maybe explain Object.keys?
I just edited the code for work true. Owner of question should edit for himself..
@SagarV It is true that he also could explain why the square brackets should be used, however then the answer from Durga should be updated/downvoted as well
@Icepickle Durga's answer -> donwvoted -> he edited it -> upvoted
@SagarV True :) I also upvoted both answers ;) Nice that you were so consistent
2

var npi = {
            code1: 'sm1',
            code2: 'sm8',
            code3: 'sm9',
            code4: ''
          }

var arr = [];
for (var i =1;i<= 3;i++) {
  arr.push(npi['code'+i]);
}
console.log(arr)

For your case Iterate from 1 to 3, and get value from obj like npi['code'+i], here you need to use bracket as Property_accessors, because it takes value as string.

Comments

2

You can use Object.keys() method and a forEach() loop:

var npi = {
  code1: 'sm1',
  code2: 'sm8',
  code3: 'sm9',
  code4: ''
}
var arr = [];

Object.keys(npi).forEach(function(key) {
    if(npi[key] != ''){
      arr.push(npi[key]);
    }
});
console.log(arr);

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

The reason why your code is not working, is because when trying to get the values of an object using . notation, the property can't be a string(when you concatenate using +''+ you practically convert the object property into a string). String works only in case of []. For example:

arr.push(npi.code + '' + i); //returns undefined
arr.push(npi['code' + i]); //returns your value

8 Comments

@SagarV, oh, ok, you're right. Corrected my answer accordingly.
Actually, you didn't, you only excluded possible empty values (which was not the question)
I retracted the vote. But FYI you should break it when it complete 3 iterations.
I understand what you're saying, but where is the logic?! I think that what the OP is intending, is to push non-empty elements into the new array. The original array may contain multiple elements, not just 4. I think my example applies on more levels and is more dynamic. You can give as many downvotes as you want, but I think this is the better answer.
@SagarV, oh, ok. Sorry for that. My bad.
|
1

First of all, if you would like to append to the object key, you should use npi['code' + i] instead of npi.code+i. Because npi.code+i means appending the value of (i) to the value of the key (code) in npi, which doesn't exist.

Second of all, you should loop starting from i = 1 instead of i = 0. So that the loop starts with npi['code1'] not npi['code0'] which also doesn't exist.

Also, the loop condition should be i < 4 instead of i < 3 so that the loop ends after i = 3 instead of i = 2

var arr = [];

for (var i = 1 ; i < 4 ; i++) {
    arr.push(npi['code' + i]);
}
console.log(arr);

Comments

0

Try This

var arr = [];
for (var i =0;i< 3;i++) {
  arr.push(npi['code'+i]);
}

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.