Friday, 15 January 2010

javascript - How to filter/search multidimensional array of objects? -



javascript - How to filter/search multidimensional array of objects? -

i have info construction below:

var options = [{ name: "option one", foo: "bar", values: [{ name: "value one", value: "value", options: [{ name: "option two", values: [{ name: "value two", value: "value", options: [] }] }] }] }, { name: "option three", values: [{ name: "value three", value: "value", options: [] }] }];

i need flatten it, filter out properties don't want , maintain knowledge of depth of each object below info structure:

var flattenedfilteredoptions = [{ depth: 0, name: "option one", values: [{ name: "value one", value: "value" }] }, { depth: 1, name: "option two", values: [{ name: "value two", value: "value" }] }, { depth: 0, name: "option three", values: [{ name: "value three", value: "value" }] }];

so want properties of name, values, , value in output. can point me in right direction start or have solution?

thanks all, here did, maintain in mind configuring properties filter isn't quite in configurable, recursion worked:

function flattenoptions(optionsarray, depth, flattenedoptions) { depth = depth || 0; flattenedoptions = flattenedoptions || []; (var = 0; < optionsarray.length; i++) { var alternative = optionsarray[i]; var nextdepth = depth + 1; var flattenedoption = { depth: depth, name: option.name, values: flattenvalues(option.values, nextdepth, flattenedoptions) }; flattenedoptions.push(flattenedoption); } homecoming flattenedoptions; } function flattenvalues(valuesarray, nextdepth, flattenedoptions) { var values = []; (var = 0; < valuesarray.length; i++) { var value = valuesarray[i]; values.push({ name: value.name, value: value.value }); if (value.options.length > 0) { flattenoptions(value.options, nextdepth, flattenedoptions); } } homecoming values; }

javascript arrays javascript-objects

No comments:

Post a Comment