1

I'm trying to push object into an new array.

var final = [],
  temp_obj = {};

for (var i = 0; i < obj.length; i++) {

  var splitted = obj[i].split(":")[0]
  if (obj[i] != null && obj[i] != '') {
    temp_obj["name"] = splitted;
  }

  final.push(temp_obj);

}

console.log(final)

The result I got is I'm getting same result for my object, which part I did wrong?

2
  • What does the code inside of obj look like? Please also include that. Commented Dec 7, 2015 at 5:03
  • You need to include example input and the intended output. Commented Dec 7, 2015 at 5:09

3 Answers 3

1

Assign empty temp_obj inside for loop like following code :

var final = [],temp_obj;  

for (var i = 0; i < obj.length; i++) {
  temp_obj = {};
  var splitted = obj[i].split(":")[0]
  if (obj[i] != null && obj[i] != '') {
     temp_obj["name"] = splitted;
  }

  final.push(temp_obj);
}

console.log(final)
Sign up to request clarification or add additional context in comments.

6 Comments

where does this obj come from ? The one with obj.lenght
@FurkanOrhan Another references of course. Assumed for loop already in action. OP problem is The result I got is I'm getting same result for my object, we know that for loop already iterated.
@FurkanOrhan that's something you should ask OP
I think there is no point declaring temp_obj outside of the loop!
@RayonDabre that's my mistake.
|
0

Try to get your null and empty checking condition to one step to the top. Like below, other vice you will get null point issues.

  var final = [],
  temp_obj = {};

for (var i = 0; i < obj.length; i++) {
   temp_obj = {};

  if (obj[i] != null && obj[i] != '') {
    var splitted = obj[i].split(":")[0]
    temp_obj["name"] = splitted;
  }

  final.push(temp_obj);

}

console.log(final)

Comments

0

The final.push() should be inside the loop (demo)

var obj = [ 'a:b', 'c:d', 'e:f' ], // just guessing
  final = [],
  temp_obj = {};

for (var i = 0; i < obj.length; i++) {

  var splitted = obj[i].split(":")[0];
  if (obj[i] !== null && obj[i] !== '') {
    temp_obj.name = splitted;
    final.push( temp_obj );
  }

}

console.log(final);

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.