How to Loop Through Json Array and Get Specific Values

How to loop through JSON array and get specific values

in your loop:

for (x in myObj) {
alert(x.car1);
}

x is the string value of key of your object. In order to get the car1 property of your nested object you can change your loop as:

for (x in myObj) {
alert(myObj[x].car1);
}

It is also a good practice to use hasOwnProperty while using for-in loop it might also iterate over properties which are in your object's prototype chain.

for (x in myObj) {
if (myObj.hasOwnProperty(x)) {
alert(myObj[x].car1);
}
}

Loop through JSON ARRAY and get value with node.js

In mean time I found a very easy way to get value from json array as follow:

Important NOTE (especially for the beginners):

If you are receiving response with http request, response is coming as a text string, so you need first to convert to JSON object as be abblle to extract values from array.

Full sample of the response is written on beginig of this thread.

http request code 
...
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
const response = JSON.parse(body.toString()); //convert string to JSON object

var result = response.originalDetectIntentRequest.payload.contact.cId;
console.log(result);
return result;
});

OR:

...
var result = response.queryResult.outputContexts[0].name;
console.log(result);
return result;
});

JSON - Iterate through JSONArray

Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
public static void main(String[] args) throws Exception
{
String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

// "I want to iterate though the objects in the array..."
JSONObject outerObject = new JSONObject(jsonInput);
JSONObject innerObject = outerObject.getJSONObject("JObjects");
JSONArray jsonArray = innerObject.getJSONArray("JArray1");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);

// "...and get thier component and thier value."
String[] elementNames = JSONObject.getNames(objectInArray);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
System.out.println();
}
}
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/

How do I loop through a JSON array?

You can use for..in loops on objects to get the keys and iterate over them. Objects don't implement the Iterable interface, so for...of doesnt work. And forEach is not a method on an object, but on an array.

const json = {
"channels": {
"main": {
"id": "691548147922763825"
},
"creations": {
"id": "700390086390448148"
},
"fanart": {
"id": "691551615873843211"
},
"memes": {
"id": "691549417173680148"
}
}
}

for( let key in json.channels ) {
console.log( key, json.channels[key] )
}

Loop through json and fetch specific values in nodejs

Here I use JSON.parse so I can use the Array.map method on the data, I use Object destructuring in the callback passed to map to pull values metadata.id and entity.name into the scope of the function. I then return a single object with entity.name as a key and metadata.id as the value. The return value from map is a new array, therefore I can use Array.reduce to transform the array into a different data structure. On each iteration of reduce the parameter current will be the individual object that was returned out of each iteration of map. Because Object.keys(current) will always be of length 1 I can use destructuring to pull the only key name out & use key/name to populate the return object.

const json = `[    {      "metadata": {        "id": "vvvvvvvvvvvvv",        "url": "cccccccccccccc",        "created_at": "2019-09-06T08:40:41Z",        "updated_at": "2019-09-06T13:25:46Z"      },      "entity": {        "name": "app1",        "b_enabled": false,        "d_url": "xxxxxs"      }    },      {      "metadata": {        "id": "vvvvvvvvvvccc",        "url": "cccccccccccccc",        "created_at": "2019-09-06T08:40:41Z",        "updated_at": "2019-09-06T13:25:46Z"      },      "entity": {        "name": "app2",        "b_enabled": false,        "d_url": "xxxxxs"      }    },      {      "metadata": {        "id": "vvvvvvvvvvddd",        "url": "cccccccccccccc",        "created_at": "2019-09-06T08:40:41Z",        "updated_at": "2019-09-06T13:25:46Z"      },      "entity": {        "name": "app3",        "b_enabled": false,        "d_url": "xxxxxs"      }    },      {      "metadata": {        "id": "vvvvvvvvvveee",        "url": "cccccccccccccc",        "created_at": "2019-09-06T08:40:41Z",        "updated_at": "2019-09-06T13:25:46Z"      },      "entity": {        "name": "app4",        "b_enabled": false,        "d_url": "xxxxxs"      }    },      {      "metadata": {        "id": "vvvvvvvvvvfff",        "url": "cccccccccccccc",        "created_at": "2019-09-06T08:40:41Z",        "updated_at": "2019-09-06T13:25:46Z"      },      "entity": {        "name": "app5",        "b_enabled": false,        "d_url": "xxxxxs"      }  }  ]`;
const result = JSON.parse(json) .map(({ metadata: { id }, entity: { name } }) => { return { [name]: id }; }) .reduce((prev, current) => { const [name] = Object.keys(current);
prev[name] = current[name];
return prev; }, {});
console.log(result);

How to loop through json object with specific key and value in javascript?

Simply you can iterate and filter data with if condition.

var my_products = {    "products": [        {            "title": "Product 1",            "id": 001,            "stock_quantity": 0,            "in_stock": false        },        {            "title": "Product 2",            "id": 002,            "stock_quantity": 0,            "in_stock": false        },        {            "title": "Product 3",            "id": 003,            "stock_quantity": 1,            "in_stock": true        },        {            "title": "Product 4",            "id": 004,            "stock_quantity": 1,            "in_stock": true        }    ]};var filterData = [];$.each(my_products.products, function(){    if (this.in_stock && this.stock_quantity === 1) {        filterData.push(this);    }});console.log(filterData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

PHP loop through JSON array and get key value pair

$jsonArray->entries is not a valid array value from the code you posted, just change it to:

public function select_from_fact_sighting($whereArray) {

...
$jsonArray = json_decode($whereArray, true);
$elementCount = count($jsonArray);

$where = array();

foreach($jsonArray as $row) {
foreach($row as $key => $val) {
$where[] = $key . " = " . $val;
}
}
....

Loop through JSON array of objects and get the properties based on the matching IDs from objects

changed answer to fit your needs:

var data = [
{
"digital_assets": [
{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},
{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}
]
},
{
"products": [
{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},
{
"id": ["BB002","AA002"],
"ProductName": "PROD 555"
}
]
}
]
let matchingIds = [];
let data_assetsObject = data.find(element => {
return Object.keys(element).includes("digital_assets")
})
let productsObject = data.find(element => {
return Object.keys(element).includes("products")
})
data_assetsObject["digital_assets"].forEach(da => {
productsObject["products"].forEach(product => {
if (product.id.includes(da.id)){
matchingIds.push({
url: da.url,
productName: product.ProductName
})
}
})
})
console.log(matchingIds);

working fiddle: https://jsfiddle.net/z2ak1fvs/3/

Hope that helped. If you dont want to use a new array, you could also store the respective data within the element you are looping through.

Edit:
I think i know why i got downvoted. My example works by making data an object, not an array. changed the snippet to show this more clearly.
Why is data an array anyway? Is there any reason for this or can you just transform it to an object?

Edit nr2:
changed the code to meet the expectations, as i understood them according to your comments. it now uses your data structure and no matter whats in data, you can now search for the objects containing the digital_assets / products property.

cheers



Related Topics



Leave a reply



Submit