[Solved] how to create a new array from existing array in javascript


So you can build out a new javascript object, but it might be tricky if you have object attributes of ‘items’ repeated over in the same object. I fixed this by making the results have an array of items like so.

The algorithm is using a double for loop so it would be expensive for large json sizes, but it works.

Here’s the code and output assuming the json object to be sorted is named ‘obj’.

var newObj = {"clause":[]};
var i,j;
for(i = 0; i < obj.clause.length; i++){
  var current = obj.clause[i];
  for(j = 0; j < newObj.clause.length; j++){
    if(newObj.clause[j].cls && newObj.clause[j].cls["clause_id"] == current["clause_id"]){
      var subObj = {"claud_item_id": current["clause_item_id"], "item_text": current["item_text"], "item_photo": current["item_photo"]};    
      newObj.clause[j].items.push(subObj);
      break;
    }
  }
  if(j == newObj.clause.length){
    var subObj = {"cls": {"clause_id": current["clause_id"], "clause_text": current["clause_text"]}, 
                  "items": [{"claud_item_id": current["clause_item_id"], "item_text": current["item_text"], "item_photo": current["item_photo"]}]};     
    newObj.clause.push(subObj);
  }
}

Here’s the value of newObj.

{
"clause": [{
    "cls": {
        "clause_id": 1,
        "clause_text": "A"
    },
    "items": [{
        "claud_item_id": 1,
        "item_text": "this text is related to clause 1 ",
        "item_photo": ""
    }]
}, {
    "cls": {
        "clause_id": 2,
        "clause_text": "B"
    },
    "items": [{
        "claud_item_id": 2,
        "item_text": "this text is related to clause 2 ",
        "item_photo": ""
    }, {
        "claud_item_id": 3,
        "item_text": "this text is related to clause 2",
        "item_photo": ""
    }, {
        "claud_item_id": 4,
        "item_text": "this text is related to clause 2",
        "item_photo": ""
    }]
}, {
    "cls": {
        "clause_id": 3,
        "clause_text": "C"
    },
    "items": [{
        "claud_item_id": 5,
        "item_text": "this text is related to clause 3",
        "item_photo": ""
    }, {
        "claud_item_id": 6,
        "item_text": "this text is related to clause 3",
        "item_photo": ""
    }, {
        "claud_item_id": 7,
        "item_text": "this text is related to clause 3",
        "item_photo": ""
    }]
}]
}

1

solved how to create a new array from existing array in javascript