Pushing to a JavaScript array via key -
i have object formatted follows;
$scope.data = [ { key: "control", values: [ ] }, { key: "experiment", values: [ ] } ];
i want able push either 1 of these arrays giving key value.
i've tried;
$scope.data.keys("experiment").values.push(thing);
but undefined. sure isn't hard i'm having trouble finding answer on here or via js documentation
the reason i'm doing in way because js library i'm using expects data in specific way
not efficiant short:
$scope.data.filter(function(v){return v.key == "experiment"})[0].values.push(thing)
a fast way it:
for (var = $scope.data.length; i--;) { if ($scope.data[i].key == "experiment") { $scope.data[i].values.push("one more thing") break } }
how should have done it:
$scope.data = { "control": [], "experiment": [] } $scope.data["experiment"].push("thing")
demo:
var $scope = {} $scope.data = [{ key: "control", values: [] }, { key: "experiment", values: [] }]; // short $scope.data.filter(function(v) { return v.key == "experiment" })[0].values.push("thing") // fast (var = $scope.data.length; i--;) { if ($scope.data[i].key == "experiment") { $scope.data[i].values.push("one more thing") break } } // output demo document.write("<pre>" + json.stringify($scope.data, null, "\t") + "</pre>") // !!! should do: $scope.data = { "control": [], "experiment": [] } $scope.data["experiment"].push("thing") // output demo document.write("<pre>" + json.stringify($scope.data, null, "\t") + "</pre>")
Comments
Post a Comment