如何将键路径数组返回嵌套的javascript对象中的值?

时间:2019-04-09 09:42:16

标签: javascript arrays object recursion nested

我正在尝试转换可能具有不同嵌套级别的对象:

const obj = {
    some: {
        thing: {
            good: 'yo'
        },
        one: 'else'
    },
    something: {
        bad: 'oy'
    },
    somethingtasty: 'mmm'
}

放入包含值的原始路径和值的对象数组:

const arr = [{
        path: 'some.thing.good',
        value: 'yo'
    }, {
        path: 'some.one',
        value: 'else
    }, {
        path: 'something.bad',
        value: 'oy'
    }, {
        path: 'somethingtasty',
        value: 'mmm'
    }]

我在SO上找到了一个有用的答案,可以解决类似的问题,该问题涉及不同嵌套的对象:

https://stackoverflow.com/a/2631198

但这不能解决

  • a:如何处理可变的嵌套深度
  • b:如何处理可变键

我还尝试查看lodash是否具有一种或多种有助于以下目的的方法:

https://github.com/node4good/lodash-contrib/blob/master/docs/_.object.selectors.js.md#getpath

或:

https://lodash.com/docs/4.17.11#flatMapDeep

但是,如果我不知道需要获取的值的路径,这将无济于事。

javascript中是否有一种方法可以遍历对象并将其键和值保存在数组中?

4 个答案:

答案 0 :(得分:2)

您可以使用'Error = files' is an invalid keyword argument for this function方法来创建递归函数。

reduce

答案 1 :(得分:2)

您可以采用迭代和递归的方法。

function getPathes(object, temp = '') {
    return Object
        .entries(object)
        .reduce(
            (r, [key, value]) => 
                (path =>  r.concat(value && typeof value === 'object'
                    ? getPathes(value, path)
                    : { path, value }))
                (temp + (temp && '.') + key),
            []
        );
}

const obj = { some: { thing: { good: 'yo' }, one: 'else' }, something: { bad: 'oy' }, somethingtasty: 'mmm' };

console.log(getPathes(obj));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

const obj = {
    some: {
        thing: {
            good: 'yo'
        },
        one: 'else'
    },
    something: {
        bad: 'oy'
    },
    somethingtasty: 'mmm'
}

const deepLinkFinder = (obj) => {
    let arr = []
    const getKeyPath = (obj, path) => {
        for (const key of Object.keys(obj)) {
            if (typeof obj[key] === 'object')
                getKeyPath(obj[key], path ?
                    `${path}.${key}` :
                    `${key}`)
            else
                arr.push({
                    path: path ?
                        `${path}.${key}` :
                        `${key}`,
                    value: obj[key]
                })
        }
    }
    getKeyPath(obj)
    return arr
}

console.log(deepLinkFinder(obj))

答案 3 :(得分:0)

一种可能的方法是递归地迭代const obj = { some: { thing: { good: 'yo' }, one: 'else' }, something: { bad: 'oy' }, somethingtasty: 'mmm' }; const getNested = (obj, propArr) => { const [prop, value] = Object.entries(obj)[0]; propArr.push(prop); if (typeof value === 'object') { return getNested(value, propArr); } return { path: propArr.join('.'), value }; }; const arr = Object.entries(obj) .map(([top, value]) => typeof value === 'object' ? getNested(obj, [top]) : ({ path: top, value }) ); console.log(arr);

<?php

$countrycode1 = $_GET['cc'];
$sql = "SELECT
       first_name,
       last_name,
       id,
       status,
       agency_id
       FROM customers
       WHERE (agency_id = '" . $countrycode1 . "') AND first_name LIKE '%" . $_GET['query'] . "%' LIMIT 1";
$resultset = mysqli_query($conn, $sql) or die("database error:" . mysqli_error($conn));
$json = array();
while ($rowscity = mysqli_fetch_assoc($resultset)) {
    echo $rowscity["id"]; exit; 
}
?>