1

I have a parent array lines = [] and contains a number of objects in lines.push(data); . The data is read line by line in my node application. And i split each line whenever \ slash character is found. Then change line into Objects data = {} and properties data.marker; data.value; data.children and so. Now when a line which has several \ slash characters is found i want that data.children to be a child array of objects. This is the line data after split()

    [ 'ft Some older versions read, ',
      'fqa And we are writing these things to you so that your joy will be complete. ',
      'fqb  ',
      'f*' ]

and this is my code to convert into data.children array

    data.children = [];
    //object for child
    var obj = {};
    for (var j=0; j<childArr.length; j++) {
        obj.marker = childArr[j].split(" ")[0] ;
        obj.value = childArr[j].substr(childArr[j].indexOf(' ')+1) ;                           
    }
    data.children.push(obj);

Now when i check console.log(data.children) this is what i gets

    [ { marker: 'f*', value: 'f*' }]

instead of what i need is

    [ { marker: 'ft' , value: 'Some older versions read,' },
      { marker: 'fqa', value: 'And we are writing these things to you so that your joy will be complete.' },
      { marker: 'fqb', value: 'null' },
      { marker: 'f*', value: 'null' },]

I am sure that it will be some trouble while i am pushing data into children array. Any help will be appreciated! Thanks in advance.

3
  • 1
    that's because you're pushing after the loop; add the push within your for loop Commented Mar 6, 2017 at 10:44
  • Sorry to say but i tried pushing child array with in the loop then also i am getting the same like { marker: 'f*', value: 'f*' } Commented Mar 6, 2017 at 10:48
  • you're changing properties of obj ... but it is the same obj every time you push ... you need to create a new object every iteration ... @War's answer is 90% correct ... a couple = should be : Commented Mar 6, 2017 at 10:52

5 Answers 5

2

This is the right answer i needed. Sorry for posting it very lately and appreciate all of your efforts. Thank you.

data.children = [];

var childArr = [ 'ft Some older versions read, ',
      'fqa And we are writing these things to you so that your joy will be complete. ',
      'fqb  ',
      'f*' ];

var data = {};
data.children = [];
for (var j = 0; j < childArr.length; j++) {
  let split = childArr[j].split(" ");
  data.children.push({
     marker: split[0],
     value: ((split[1] == "" ||split[1] == undefined) ? null : split.slice(1).join(" "))
  });
}
console.log(data.children);

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand you correctly you are only creating one object, then updating it, wheras you want 1 object in object.children for each item in the array "childArr" ...

data.children = [];
//object for child
var obj = {};
for (var j=0; j<childArr.length; j++) {
    var obj = {
        marker: childArr[j].split(" ")[0],
        value: childArr[j].substr(childArr[j].indexOf(' ')+1) 
    };
    data.children.push(obj);                  
}

Or did I miss something?

3 Comments

you missed javascript object literal syntax 101 :p
there you go (also, loose the = {} outside the loop, and the var inside the loop and you're golden :p
@War i tried your suggestion but getting SyntaxError: Invalid shorthand property initializer
0

var childArr = ['ft Some older versions read, ',
    'fqa And we are writing these things to you so that your joy will be complete. ',
    'fqb  ',
    'f*'
  ],
  data = {
    children: []
  };
for (var j = 0; j < childArr.length; j++) {
  let split = childArr[j].split(" ");
  data.children.push({
    marker: split[0],
    value: split.slice(1, -1).join(" ")
  });
}

console.log(data.children);

Comments

0

Try using Array#forEach to iterate over all the array elements.Find the index of first space to separate keys and values of new objects.

   var array =     [ 'ft Some older versions read, ',
      'fqa And we are writing these things to you so that your joy will be complete. ',
      'fqb  ',
      'f*' ];
   var finalArray =[] ;
   array.forEach(function(value,index){
   var firstSpace = value.indexOf(' ');
   if(firstSpace >=0){
   var key = value.substr(0,firstSpace);
   var val = value.substr(firstSpace+1);
   }
   else{
   var key = value;
   var val = '';
   }
   var obj = {};
   obj.marker = key;
   obj.value = val;
   finalArray.push(obj);
  
   });
  console.log(finalArray);

2 Comments

but a remark, the last object came as this ` { marker: '', value: 'f*' } ` which i know to fix.
try edited answer.just make if/else condition for checking space.
0

var childArr = [ 'ft Some older versions read, ',
      'fqa And we are writing these things to you so that your joy will be complete. ',
      'fqb  ',
      'f*' ];
    var data = {};
    data.children = [];

    for (var j=0; j<childArr.length; j++) {
        var dataArr = childArr[j].split(" ");
        var obj = {};
        obj.marker = dataArr[0];
        obj.value = (dataArr.length > 1) ? childArr[j].substr(childArr[j].indexOf(' ')+1) : "";
        data.children.push(obj);              
    }

    console.log(data.children);

Try this code. Its working

Otherwise you can Check in JS Fiddle

2 Comments

i have tried this but was giving me Error while reading file.
@zachi added JS fiddle link. Check there.

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.