1

Here is the code to begin with;

Plunk

data = {
  "questions": ["Who", "Where", "How"],
  "names": ["Bill", "Fred", "Lindsey"],
  "cities": ["Baltimore", "New York", "Chicago"],

  "values": [
    [
      [50, 20, 40],
      [40, 90, 10],
      [50, 75, 30]

    ],
    [
      [33, 57, 100],
      [20, 70, 89],
      [16, 40, 68]
    ],
    [
      [3, 26, 54],
      [62, 69, 86],
      [23, 81, 98]
    ]
  ]
}

function sortObject() {
  var values;

  var question = data.questions.indexOf("Who", "Where")
  var name = data.names.indexOf("Bill");
  var city = data.cities.indexOf("Baltimore");

  values = data.values[question][name][city]
  console.log(values)
}

sortObject()

I would like to be able to return the results for both "Who" & "Where" whilst excluding "How".

So the final result would be [50, 33].

I would also like the method to be able to work with an infinite amount of items, so for instance there could be 100 items in the "questions" array and I would be able to individually pick whichever ones I would like to show regardless of their position inside the array.

I think that I will have to loop through each item and then perhaps do something along the lines of;

  for (var question = 0; question < data.questions.length; question++) {
    if (data.questions.indexOf() == "Who" || "Where") {
      var name = data.names.indexOf("Bill");
      var city = data.cities.indexOf("Baltimore");
      values = data.values[question][name][city]
      console.log(values)
    }
  }

But this is not working, so I'm not sure where to go from here?

Hope everything is clear, please let me know if you need any more information;

Thanks in advance for any help/advice!

alexc
  • 1,250
  • 2
  • 17
  • 44
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Teemu Jul 01 '16 at 09:14

2 Answers2

2

You could iterate over if there are more than one items to search for.

function getData(question, name, city) {
    var result = [];

    (Array.isArray(question) ? question : [question]).forEach(function (q) {
        var r = data.values[data.questions.indexOf(q)] || [];
        (Array.isArray(name) ? name : [name]).forEach(function (n) {
            var rr = r[data.names.indexOf(n)] || [];
            (Array.isArray(city) ? city : [city]).forEach(function (c) {
                result.push({
                    question: [q, n, c],
                    value: rr[data.cities.indexOf(c)]
                });
            });
        });
    });
    return result;
}

var data = { "questions": ["Who", "Where", "How"], "names": ["Bill", "Fred", "Lindsey"], "cities": ["Baltimore", "New York", "Chicago"], "values": [[[50, 20, 40], [40, 90, 10], [50, 75, 30]], [[33, 57, 100], [20, 70, 89], [16, 40, 68]], [[3, 26, 54], [62, 69, 86], [23, 81, 98]]] },
    result = getData(["Who", "Where"], "Bill", "Baltimore");

console.log(result);

Another more dynamic solution could be an iterative recursive approach with a search object.

function getData(search) {
    var result = [],
        order = ['questions', 'names', 'cities'];

    function iter(value, level) {
        if (level === order.length) {
            return result.push(value);
        }
        search[order[level]].forEach(function (a) {
            iter((value || [])[data[order[level]].indexOf(a)], level + 1);
        });
    }

    iter(data.values, 0);
    return result;
}

var data = { "questions": ["Who", "Where", "How"], "names": ["Bill", "Fred", "Lindsey"], "cities": ["Baltimore", "New York", "Chicago"], "values": [[[50, 20, 40], [40, 90, 10], [50, 75, 30]], [[33, 57, 100], [20, 70, 89], [16, 40, 68]], [[3, 26, 54], [62, 69, 86], [23, 81, 98]]] },
    result = getData({ questions: ["Who", "Where"], names: ["Bill"], cities: ["Baltimore"] });

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Hi Nina, Thanks for the answer(s)! I've been playing around with the first solution, and was wondering if it would be easy to turn it into an object this way also? like so; result.push({ question: question, value: rr[data.cities.indexOf(c)]}); });. I will start looking at the second solution now also, thanks for taking the time to help! – alexc Jul 01 '16 at 10:13
  • like the first proposal now? – Nina Scholz Jul 01 '16 at 10:17
  • Hi Nina, I have another question if it's okay? I was wondering if it could be possible to return two results, and then edit the object accordingly? e.g; `resultTest.push({do stuff})` + `result.push(do stuff)` with `return {result, resultTest};` and then `var i = getData();` - `console.log(i.result(["Who", "Where"], "Bill", "Baltimore"));` etc etc. [plnk](http://plnkr.co/edit/lzSOTIjykPRRX0WBmsQX?p=preview). I'm not sure if this would be better served as another question, or is if it is okay just to ask in a comment? – alexc Jul 05 '16 at 08:01
  • you need just one call and then log both results like `var i = getData(["Who", "Where"], "Bill", "Baltimore"); console.log(i.result); console.log(i.resultTest);`. – Nina Scholz Jul 05 '16 at 08:10
  • Hi Nina, I was wondering if you have a moment, you might be able to take at the following [plunk](http://plnkr.co/edit/m6MaNc4dy8f9ftmUYvBt?p=preview)? I'm trying to use your script to show like the second console.log. I've been trying to figure it out for a few hours now, with no luck.. – alexc Jul 07 '16 at 08:37
  • It should only return 3 arrays as there are only 3 dates, and each array should only have 2 objects inside because of the `Array.isArray(question + result = getData(["Who", "Where"]);` – alexc Jul 07 '16 at 08:58
  • you have mixup of foreach loops and for loops and it looks like that you should have to decide which kind of loop should be used. both makes no sense. – Nina Scholz Jul 07 '16 at 09:20
  • Yes I think you are right. I think this might make a little more sense? [plunk](http://plnkr.co/edit/m6MaNc4dy8f9ftmUYvBt?p=preview). So, I'm just trying to use the same code as the working formula (commented out in the plnk) but restrict it only looping over the questions set by the questions forEach loop. Perhaps I could set the questions to be iterated over within the forEach loop? like so; `(Array.isArray(question) ? question : ["Who", "Where"]).forEach(function(q)` – alexc Jul 07 '16 at 09:35
  • what do you like to achieve? do you like to use default values? or what is the purpose of `Array.isArray(question) ? question : ["Who", "Where"])...`? – Nina Scholz Jul 07 '16 at 09:47
  • The purpose would be to dynamically change the data array in the context of the loops. I think I may have figured it out! (Thanks in the most part to your questions making me think about the code differently). Here is the [plunk](http://plnkr.co/edit/m6MaNc4dy8f9ftmUYvBt?p=preview). I think it makes sense this way? – alexc Jul 07 '16 at 10:00
0

Try to change your code like this:

function sortObject() {
  var values = [];

  var whoIndex = data.questions.indexOf("Who");
  var whereIndex = data.questions.indexOf("Where");
  var name = data.names.indexOf("Bill");
  var city = data.cities.indexOf("Baltimore");

  values.push(data.values[whoIndex][name][city]);
  values.push(data.values[whereIndex][name][city]);
  console.log(values); //[50, 33]
}
Arg0n
  • 8,283
  • 2
  • 21
  • 38