By Zienu


2019-01-11 12:05:03 8 Comments

Is there a simpler way to retrieve the value "TestProject" in the JSON response rather than using a for loop in my code?

[
    {
        "Id": "9ac44c1d-0066-47aa-a2a2-a9b90109b0a5",
        "Group": null,
        "DataFields": [
            {
                "Header": "ProjectID",
                "Value": "TestProject"
            },
            {
                "Header": "uui_ConfigPack",
                "Value": "75e8ce5a-7ae0-41ca-86f0-aca1e7158073"
            }
        ],
        "HasDocuments": null
    }
]
var projResults = JSON.parse(responseBody);

var projNumber = 1;

dataProjectId = projResults[projNumber].Id;

projName = 'Not Found';
for (i = 0; i < projResults[projNumber].DataFields.length; i++)
    {
        if(projResults[projNumber].DataFields[i].Header == "ProjectID")
        {
            projName = projResults[projNumber].DataFields[i].Value;
        }
    }

3 comments

@jcal 2019-01-11 12:14:01

You can use higher order functions like map filter reduce etc. to avoid for-loops.

here is a 1 liner:

var obj = [
    {
        "Id": "9ac44c1d-0066-47aa-a2a2-a9b90109b0a5",
        "Group": null,
        "DataFields": [
            {
                "Header": "ProjectID",
                "Value": "TestProject"
            },
            {
                "Header": "uui_ConfigPack",
                "Value": "75e8ce5a-7ae0-41ca-86f0-aca1e7158073"
            }
        ],
        "HasDocuments": null
    }
]

console.log(obj.map(i => i.DataFields).flat(1).find(i => i.Header === 'ProjectID').Value);


As stated by CertainPerformance and vlaz. This will lead to bad performance because of multiple iterations.

But if you like a declarative coding style you can use RxJS in which you can do something like:

var obs$ = from(obj);
obs$.pipe(
  flatMap(i => i.DataFields),
  filter(i => i.Header === 'ProjectID' )),
  pluck('Value')
).subscribe(console.log);

which basically does the same thing but in a more performant way.

@CertainPerformance 2019-01-11 12:15:35

This constructs two unnecessary intermediate arrays and will throw an error if no match is found.

@vlaz 2019-01-11 12:22:19

"a 1 liner" - that contains three distinct operations traversing the array each time. The fact that you can put all that in one line doesn't mean you should. Because if the amount of lines is your only metric, then any minifier will also turn an entire file into a single line, thus the code would be equally good.

@Ayman THEE 2019-01-11 12:10:07

I would suggest reading about Array methods like:

  • map
  • filter
  • reduce ... the functions will help you manage your arrays in an efficient way, it will make your code looks cleaner, and easy to read, you will find more information about it here:

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map

And i do suggest the 'javascript 30' of wesbos, he has a wonderful video about it :)

@CertainPerformance 2019-01-11 12:08:56

It looks like you're trying to find an object in an array, for which the most idiomatic method to use is Array.prototype.find:

var projResults = [
    {
        "Id": "9ac44c1d-0066-47aa-a2a2-a9b90109b0a5",
        "Group": null,
        "DataFields": [
            {
                "Header": "ProjectID",
                "Value": "TestProject"
            },
            {
                "Header": "uui_ConfigPack",
                "Value": "75e8ce5a-7ae0-41ca-86f0-aca1e7158073"
            }
        ],
        "HasDocuments": null
    }
];
var projNumber = 0;
const foundObj = projResults[projNumber].DataFields.find(({ Header }) => Header === 'ProjectID');
const projName = foundObj ? foundObj.Value : 'Not Found';
console.log(projName);

Related Questions

Sponsored Content

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

30 Answered Questions

[SOLVED] How to append something to an array?

72 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5393353 View
  • 6715 Score
  • 72 Answer
  • Tags:   javascript arrays

29 Answered Questions

[SOLVED] For-each over an array in JavaScript?

51 Answered Questions

44 Answered Questions

33 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

37 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

63 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

39 Answered Questions

[SOLVED] Sort array of objects by string property value

Sponsored Content