JavaScript array_replace_recursive
!No description available for array_replace_recursive. @php.js developers: Please update the function summary text file.
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 | function array_replace_recursive (arr) { // + original by: Brett Zamir (http://brett-zamir.me) // * example 1: array_replace_recursive({'citrus' : ["orange"], 'berries' : ["blackberry", "raspberry"]}, {'citrus' : ['pineapple'], 'berries' : ['blueberry']}); // * returns 1: {citrus : ['pineapple'], berries : ['blueberry', 'raspberry']} if (arguments.length < 2) { throw new Error('There should be at least 2 arguments passed to array_replace_recursive()'); } // Although docs state that the arguments are passed in by reference, it seems they are not altered, but rather the copy that is returned (just guessing), so we make a copy here, instead of acting on arr itself var retObj = {}; for (var prop in arr) { retObj[prop] = arr[prop]; } for (var i = 1; i < arguments.length; i++) { for (var p in arguments[i]) { if (typeof retObj[p] === 'object' && retObj[p] !== null) { retObj[p] = this.array_replace_recursive(retObj[p], arguments[i][p]); } else { retObj[p] = arguments[i][p]; } } } return retObj; } |
Examples
Running
1 | array_replace_recursive({'citrus' : ["orange"], 'berries' : ["blackberry", "raspberry"]}, {'citrus' : ['pineapple'], 'berries' : ['blueberry']}); |
Should return
1 | {citrus : ['pineapple'], berries : ['blueberry', 'raspberry']} |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have array_replace_recursive goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>