0

I'm trying to create an object structure like this "price": { "minPrice": 1000, "maxPrice": 10000 }, from a dot nation passed in a URL ( price.minPrice=4000 ). "price" could be any value passed from the first part of the notation.

I using the code below but it wont create the required out come. Also when I update the value if should return "price": { "minPrice": updatedvalue , "maxPrice": updatedvalue } not { "minPrice": updatedvalue} or { "maxPrice": updatedvalue }

function getUrlDotNotation(key, value) {

        var arr = key.split('.'),
        var label = arr[0],
        queryParams = {};


        for (var i = 0; i < arr.length - 1; i++) {
            vm.queryParams = vm.queryParams[arr[i]] = {};
        }

        vm.queryParams[arr[arr.length - 1]] = value;

        return vm.queryParams;
    }


    $scope.$watch('vm.modelMin', function onSliderMinChange(newValue, oldValue) {
        if (isSearchResultsPage) {
            if (newValue !== oldValue && !_.isNaN(newValue) && !_.isNaN(oldValue)) {
                getUrlDotNotation(vm.firstHandleBackendVar, vm.options[newValue].value);
            }
        }
    });

    $scope.$watch('vm.modelMax', function onSliderMaxChange(newValue, oldValue) {
        if (isSearchResultsPage) {
            if (newValue !== oldValue && !_.isNaN(newValue) && !_.isNaN(oldValue)) {
                getUrlDotNotation(vm.secondHandleBackendVar, vm.options[newValue].value);
            }
        }
    });
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66

1 Answers1

0

The problem is that you're overwriting vm.queryParams on each iteration, a "sliding" pointer should be a separate variable, e.g.

function makeObject(key, value) {
  let 
    obj = {}, 
    o = obj,
    keys = key.split('.'),
    last = keys.pop();
  
  for (let k of keys)
    o = o[k] = {};
  
  o[last] = value;
  return obj;
}


console.log(makeObject('foo.bar.baz', 42))
georg
  • 211,518
  • 52
  • 313
  • 390