2

I want to access salesId of json array but sales is an array also, so do loop twice?

var json = [
  {
    'id':1,
    'sales':
    [
      {'salesId':123},
      {'salesId':456}

    ]
  },
  {
    'id':2,
   'sales':
   [
      {'salesId':789},
      {'salesId':111213}

    ]
  }
];

6 Answers 6

1
for (var i in json) {
   for (var j in json[i].sales) {
      var result = json[i].sales[j].salesId; // here "result" will get salesId
   }
}

See by yourself : here

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

Comments

1

How do you want the output?

json.map(function(x){ return x.sales.map(function(y){return y.salesId})})

returns ids per object

"[[123,456],[789,111213]]"

Comments

1

You can use inner loop instead, incase salesId is dynamic in sales.

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

    salesItem = json[i].sales;

    for(var j=0;j<salesItem.length;j++){

        var item = salesItem[j];
        console.log(item.salesId);

    }
}

Comments

1

If you don't care about the id you could simply flatten the array like so:

var newArray = json.reduce(function(p,c,i){
    return i>1 ? p.concat(c.sales) : p.sales.concat(c.sales);
});

which will give you:

[ // newArray
    {'salesId':123},
    {'salesId':456},
    {'salesId':789},
    {'salesId':111213}
]

You could also use reduce to return just an array of salesId too if you wanted.

Comments

1

You don't need to loop twice

//loop through the json array that holds objects
for (var i=0; i<json.length; i++) {
 var obj = json[i]; //reference to each object
 var sales = obj.sales;
 sales.forEach(function(element, index) {
     console.log(element.salesId);
 });
}

Comments

1

Here are two other ways. Not suggesting these are better, just 'other' ways.

var json = [
  {
    'id':1,
    'sales':
    [
      {'salesId':123},
      {'salesId':456}

    ]
  },
  {
    'id':2,
   'sales':
   [
      {'salesId':789},
      {'salesId':111213}

    ]
  }
];

one way:

var results = [];

    for(i=0;i<json.length;i++){
      results.push ( JSON.stringify(json[i].sales).match(/(\d+)/g,function($1){
            return $1
        }))
     };

results; // [["123", "456"], ["789", "111213"]]

another way:

var str;
for(i=0;i<json.length;i++){
      str =  str + JSON.stringify(json[i].sales);
};
 str = str.match(/(\d+)/g,function($1){
            return $1
 })
str; //["123", "456", "789", "111213"]

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.