1

This is my array:

[
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['F', "_180"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4]
    ['F', "_360"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['m', 5]
    ['F', "_480"],
]

This is what I want to achieve:

[{
    profile_180: {
        x: 1,
        y: 2,
        z: 3
    }
}, {
    profile_360: {
        x: 1,
        y: 2,
        z: 3,
        t: 4
    }
}, {
    profile_480: {
        x: 1,
        y: 2,
        z: 3
        t: 4,
        m: 5
    }
}]

How do I get this?

1
  • 2
    Down vote without a comment is really useless. You have a problem with array questions? :s Commented Mar 22, 2016 at 6:13

3 Answers 3

2

data = [
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['F', "_180"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['F', "_360"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['m', 5],
    ['F', "_480"],
];

var result = {};
var current = {};
data.forEach(function(row) {
  if (row[0] == 'F') {
    result['profile' + row[1]] = current;
    current = {};
  } else {
    current[row[0]] = row[1];
  }
});
console.log(result);
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

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

1 Comment

Err, actually I had updated my question but you were so fast to answer it I guess, you haven't seen the updated version.
1

You can do it by,

var res = [], tmp = {}, obj = {};
x.forEach(function(itm,i) {
 if(itm[0] !== "F"){
  tmp[itm[0]] = itm[1];
 } else {
   obj["profile_" + itm[1]] = tmp;
   res.push(obj);
   tmp = {}, obj ={};
 }
});

where x is the array that contains the data.

2 Comments

This is exactly what I needed. Thank you!
@scaryguy Glad to help! :)
0

try this

var obj = [
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['F', "_180"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['F', "_360"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['m', 5],
    ['F', "_480"],
];
var output = [];
var tmpArr = {};
obj.forEach(function(value,index){

   console.log(value);
   if (value[0] != 'F' )
   {
      tmpArr[value[0]] = value[1];
   }
   else
   {
     var profileValue = "Profile_" + value[1];
     var tmpObj = {};
     tmpObj[profileValue] = tmpArr;
      output.push( tmpObj );
      tmpArr = {};
   }
});
document.body.innerHTML += JSON.stringify(output,0,4);

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.