0

i have javascript tree object and i want to convert it to list array

My tree:

jsfiddle

how to get 'href' value and push it to an array list ?

var res=['hrefValue','hrefValue','hrefValue','hrefValue','hrefValue','hrefValue'];
4
  • Can you let us know more about your question? Commented Feb 11, 2017 at 3:38
  • JavaScript doesn't have array list, but it does have Arrays with similar functionality. Commented Feb 11, 2017 at 3:45
  • Also why are you trying to wrap this into a single array item and then into a string with '[{...}]'? Remove the quotes '[ .... ]', the ' quote doesn't support multi-line string and there is no reason to do that. It's not supported to be a big string, and will not function right if you have it like that. Commented Feb 11, 2017 at 3:49
  • Consider using this library it contains functions to convert from tree data to array and vise versa. npmjs.com/package/@dsinjs/binary-tree, it has functions like fromArray(), toArray(). Commented Nov 29, 2020 at 19:19

3 Answers 3

1
function convert(tree){
    return tree.reduce(function(acc, o) {       // check the docs for reducs in the link bellow
        if(o.href)                              // if this object has an href
            acc.push(o.href);                   // add the href to the result array
        if(o.nodes)                             // if this object has children
            acc = acc.concat(convert(o.nodes)); // get their href and add (concat) them to the result
        return acc;
    }, []);
}
  • tree should be an array not a string, if you have it as a string (JSON string) then you have to parse it before passing it to the function using JSON.parse.

  • Javascript doesn't have ArrayLists, it only have arrays.

  • Here is the link to the docs of Array.prototype.reduce.

  • Here is a working fiddle.

Sign up to request clarification or add additional context in comments.

Comments

1
var getHrefs = function(nodes) {
    return nodes.reduce(function (arr, node) {
        return arr.concat(node.href).concat(node.nodes ? getHrefs(node.nodes) : []);
    }, []);
}

var hrefs = getHrefs(tree);   // ["7400.34.03.00.00.00", "7400.34.03.01.00.00", ... etc.]

1 Comment

Please provide some explanation about your question , code only answers are not so useful.
1

You can use Array.prototype.map(), spread element

let res = [];
tree.map(({href, nodes}) => res = [...res, href, ...nodes.map(({href:h}) => h)]);
// do stuff with `res`

jsfiddle https://jsfiddle.net/4ajr1spr/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.