使用字符串键访问嵌套的JavaScript对象

时间:2011-06-27 10:25:03

标签: javascript jquery path nested

我有这样的数据结构:

var someObject = {
    'part1' : {
        'name': 'Part 1',
        'size': '20',
        'qty' : '50'
    },
    'part2' : {
        'name': 'Part 2',
        'size': '15',
        'qty' : '60'
    },
    'part3' : [
        {
            'name': 'Part 3A',
            'size': '10',
            'qty' : '20'
        }, {
            'name': 'Part 3B',
            'size': '5',
            'qty' : '20'
        }, {
            'name': 'Part 3C',
            'size': '7.5',
            'qty' : '20'
        }
    ]
};

我想使用这些变量访问数据:

var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";

part1name应填充someObject.part1.name的值,即“第1部分”。 part2quantity与60相同。

无论如何用纯javascript或JQuery来实现这个目标吗?

40 个答案:

答案 0 :(得分:466)

我刚刚根据我已经拥有的一些类似代码制作了它,它似乎有用:

Object.byString = function(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}

用法::

Object.byString(someObj, 'part3[0].name');

查看http://jsfiddle.net/alnitak/hEsys/

上的工作演示

编辑有些人注意到,如果传递的字符串中最左边的索引与对象中正确嵌套的条目不对应,则此代码将抛出错误。这是一个有效的问题,但是IMHO在调用时最好用try / catch块来解决,而不是让这个函数以无效索引的方式静默返回undefined

答案 1 :(得分:152)

这是我使用的解决方案:

function resolve(path, obj=self, separator='.') {
    var properties = Array.isArray(path) ? path : path.split(separator)
    return properties.reduce((prev, curr) => prev && prev[curr], obj)
}

使用示例:

// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)

// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'

// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})

// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42

// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42

限制:

  • 不能对数组索引使用括号([]) - 尽管在分隔符令牌之间指定数组索引(例如,.)可正常工作,如上所示。

答案 2 :(得分:148)

lodash现在使用_.get(obj, property)支持此功能。见https://lodash.com/docs#get

文档示例:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// → 3

_.get(object, ['a', '0', 'b', 'c']);
// → 3

_.get(object, 'a.b.c', 'default');
// → 'default'

答案 3 :(得分:61)

你必须自己解析字符串:

function getProperty(obj, prop) {
    var parts = prop.split('.');

    if (Array.isArray(parts)) {
        var last = parts.pop(),
        l = parts.length,
        i = 1,
        current = parts[0];

        while((obj = obj[current]) && i < l) {
            current = parts[i];
            i++;
        }

        if(obj) {
            return obj[last];
        }
    } else {
        throw 'parts is not valid array';
    }
}

这要求您还使用点表示法定义数组索引:

var part3name1 = "part3.0.name";

它使解析更容易。

DEMO

答案 4 :(得分:39)

也适用于对象内的数组/数组。 防范无效价值。

/**
 * Retrieve nested item from object/array
 * @param {Object|Array} obj
 * @param {String} path dot separated
 * @param {*} def default value ( if result undefined )
 * @returns {*}
 */
function path(obj, path, def){
    var i, len;

    for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
        if(!obj || typeof obj !== 'object') return def;
        obj = obj[path[i]];
    }

    if(obj === undefined) return def;
    return obj;
}

//////////////////////////
//         TEST         //
//////////////////////////

var arr = [true, {'sp ace': true}, true]

var obj = {
  'sp ace': true,
  arr: arr,
  nested: {'dotted.str.ing': true},
  arr3: arr
}

shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>

答案 5 :(得分:21)

使用eval:

var part1name = eval("someObject.part1.name");

换行以在错误时返回undefined

function path(obj, path) {
    try {
        return eval("obj." + path);
    } catch(e) {
        return undefined;
    }
}

http://jsfiddle.net/shanimal/b3xTw/

在挥舞着eval的力量时,请使用常识和谨慎。它有点像光剑,如果你把它转过来,你有90%的机会切断肢体。它不适合所有人。

答案 6 :(得分:16)

您可以设法使用点符号获取深层对象成员的值,而无需使用任何外部JavaScript库,只需使用以下简单技巧:

new Function('_', 'return _.' + path)(obj);

如果要从part1.name获取someObject的值,请执行以下操作:

new Function('_', 'return _.part1.name')(someObject);

这是一个简单的小提琴演示:https://jsfiddle.net/harishanchu/oq5esowf/

答案 7 :(得分:9)

这可能永远都不会出现……但是无论如何,这还是

  1. []替换.括号语法
  2. 拆分为.个字符
  3. 删除空白字符串
  4. 找到路径(否则为undefined

// "one liner" (ES6)

const deep_value = (obj, path) => 
  path
    .replace(/\[|\]\.?/g, '.')
    .split('.')
    .filter(s => s)
    .reduce((acc, val) => acc && acc[val], obj);
    
// ... and that's it.

var someObject = {
    'part1' : {
        'name': 'Part 1',
        'size': '20',
        'qty' : '50'
    },
    'part2' : {
        'name': 'Part 2',
        'size': '15',
        'qty' : '60'
    },
    'part3' : [
        {
            'name': 'Part 3A',
            'size': '10',
            'qty' : '20'
        }
        // ...
    ]
};

console.log(deep_value(someObject, "part1.name"));               // Part 1
console.log(deep_value(someObject, "part2.qty"));                // 60
console.log(deep_value(someObject, "part3[0].name"));            // Part 3A

答案 8 :(得分:7)

在这里,我提供了更多方法,在许多方面看起来更快:

选项1:拆分字符串。或[或]或&#39;或&#34;,反转它,跳过空白项目。

function getValue(path, origin) {
    if (origin === void 0 || origin === null) origin = self ? self : this;
    if (typeof path !== 'string') path = '' + path;
    var parts = path.split(/\[|\]|\.|'|"/g).reverse(), name; // (why reverse? because it's usually faster to pop off the end of an array)
    while (parts.length) { name=parts.pop(); if (name) origin=origin[name]; }
    return origin;
}

选项2(最快,除了eval):低级字符扫描(没有正则表达式/分割/等,只是快速字符扫描)。 注意:此版本不支持索引引用。

function getValue(path, origin) {
    if (origin === void 0 || origin === null) origin = self ? self : this;
    if (typeof path !== 'string') path = '' + path;
    var c = '', pc, i = 0, n = path.length, name = '';
    if (n) while (i<=n) ((c = path[i++]) == '.' || c == '[' || c == ']' || c == void 0) ? (name?(origin = origin[name], name = ''):(pc=='.'||pc=='['||pc==']'&&c==']'?i=n+2:void 0),pc=c) : name += c;
    if (i==n+2) throw "Invalid path: "+path;
    return origin;
} // (around 1,000,000+/- ops/sec)

选项3::扩展选项2以支持报价 - 有点慢,但仍然很快)

function getValue(path, origin) {
    if (origin === void 0 || origin === null) origin = self ? self : this;
    if (typeof path !== 'string') path = '' + path;
    var c, pc, i = 0, n = path.length, name = '', q;
    while (i<=n)
        ((c = path[i++]) == '.' || c == '[' || c == ']' || c == "'" || c == '"' || c == void 0) ? (c==q&&path[i]==']'?q='':q?name+=c:name?(origin?origin=origin[name]:i=n+2,name='') : (pc=='['&&(c=='"'||c=="'")?q=c:pc=='.'||pc=='['||pc==']'&&c==']'||pc=='"'||pc=="'"?i=n+2:void 0), pc=c) : name += c;
    if (i==n+2 || name) throw "Invalid path: "+path;
    return origin;
}

JSPerf:http://jsperf.com/ways-to-dereference-a-delimited-property-string/3

&#34;的eval(...)&#34;虽然仍然是王者(表现明智)。如果您的财产路径直接受您控制,那么使用&#39; eval&#39; (特别是如果需要速度)。如果在电线上拉动物业路径&#34; (on the line!?lol:P),然后是,使用别的东西是安全的。只有白痴会说永远不会使用&#34; eval&#34;至少,ARE good reasons何时使用它。此外,&#34;它用于Doug Crockford's JSON parser。&#34;如果输入是安全的,那么根本没有问题。使用正确的工具来完成正确的工作。

答案 9 :(得分:7)

我认为你要求这个:

var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 =  someObject.part3[0].name;

你可能会问这个:

var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 =  someObject["part3"][0]["name"];

两者都可以使用


或者你可能要求这个

var partName = "part1";
var nameStr = "name";

var part1name = someObject[partName][nameStr];

最后你可能会要求这个

var partName = "part1.name";

var partBits = partName.split(".");

var part1name = someObject[partBits[0]][partBits[1]];

答案 10 :(得分:6)

尽管我在搜索通过字符串路径访问AngularJS $范围属性的解决方案时找到了这个答案,但是Speigg的方法非常整洁干净,只需稍加修改即可完成工作:

$scope.resolve = function( path, obj ) {
    return path.split('.').reduce( function( prev, curr ) {
        return prev[curr];
    }, obj || this );
}

只需将此函数放在根控制器中并使用它,如下所示:

$scope.resolve( 'path.to.any.object.in.scope')

答案 11 :(得分:6)

这是带有lodash的一个班轮。

const deep = { l1: { l2: { l3: "Hello" } } };
const prop = "l1.l2.l3";
const val = _.reduce(prop.split('.'), function(result, value) { return result ? result[value] : undefined; }, deep);
// val === "Hello"

甚至更好......

const val = _.get(deep, prop);

或ES6版本w / reduce ...

const val = prop.split('.').reduce((r, val) => { return r ? r[val] : undefined; }, deep);

Plunkr

答案 12 :(得分:4)

以防万一,有人在2017年或以后访问此问题并寻找易于记忆的方式,这是Accessing Nested Objects in JavaScript上一篇精巧的博客文章,而没有被迷住

无法读取未定义的属性'foo'错误

使用数组精简访问嵌套对象

让我们看一下这个示例结构

const user = {
    id: 101,
    email: 'jack@dev.com',
    personalInfo: {
        name: 'Jack',
        address: [{
            line1: 'westwish st',
            line2: 'washmasher',
            city: 'wallas',
            state: 'WX'
        }]
    }
}

要访问嵌套数组,您可以编写自己的数组reduce util。

const getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) =>
        (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}

// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);

// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.

还有一个出色的类型处理最小库typy,可以为您完成所有这些工作。

如果输入有误,您的代码将如下所示

const city = t(user, 'personalInfo.address[0].city').safeObject;

免责声明:我是该软件包的作者。

答案 13 :(得分:3)

我还没找到一个用字符串路径完成所有操作的包,所以我最终编写了自己的快速小包,它支持insert(),get()(默认返回),set ()和remove()操作。

您可以使用点表示法,括号,数字索引,字符串编号属性和带有非单词字符的键。简单用法如下:

> var jsocrud = require('jsocrud');

...

// Get (Read) ---
> var obj = {
>     foo: [
>         {
>             'key w/ non-word chars': 'bar'
>         }
>     ]
> };
undefined

> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'

https://www.npmjs.com/package/jsocrud

https://github.com/vertical-knowledge/jsocrud

答案 14 :(得分:3)

如果您想要一个可以正确检测和报告路径解析任何问题的详细信息的解决方案,我为此编写了自己的解决方案 - 库 path-value

const {resolveValue} = require('path-value');

resolveValue(someObject, 'part1.name'); //=> Part 1
resolveValue(someObject, 'part2.qty'); //=> 50
resolveValue(someObject, 'part3.0.name'); //=> Part 3A

请注意,对于索引,我们使用 .0 而不是 [0],因为解析后者会增加性能损失,而 .0 直接在 JavaScript 中工作,因此速度非常快。< /p>

但是,也支持完整的 ES5 JavaScript 语法,只需先对其进行标记:

const {resolveValue, tokenizePath} = require('path-value');

const path = tokenizePath('part3[0].name'); //=> ['part3', '0', 'name']

resolveValue(someObject, path); //=> Part 3A

答案 15 :(得分:3)

简单的函数,允许字符串或数组路径。

function get(obj, path) {
  if(typeof path === 'string') path = path.split('.');

  if(path.length === 0) return obj;
  return get(obj[path[0]], path.slice(1));
}

const obj = {a: {b: {c: 'foo'}}};

console.log(get(obj, 'a.b.c')); //foo

OR

console.log(get(obj, ['a', 'b', 'c'])); //foo

答案 16 :(得分:2)

现在有一个npm模块用于执行此操作:https://github.com/erictrinh/safe-access

使用示例:

var access = require('safe-access');
access(very, 'nested.property.and.array[0]');

答案 17 :(得分:2)

/**
 * Access a deep value inside a object 
 * Works by passing a path like "foo.bar", also works with nested arrays like "foo[0][1].baz"
 * @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e
 * Unit tests: http://jsfiddle.net/Victornpb/0u1qygrh/
 */
function getDeepVal(obj, path) {
    if (typeof obj === "undefined" || obj === null) return;
    path = path.split(/[\.\[\]\"\']{1,2}/);
    for (var i = 0, l = path.length; i < l; i++) {
        if (path[i] === "") continue;
        obj = obj[path[i]];
        if (typeof obj === "undefined" || obj === null) return;
    }
    return obj;
}

使用

getDeepVal(obj,'foo.bar')
getDeepVal(obj,'foo.1.bar')
getDeepVal(obj,'foo[0].baz')
getDeepVal(obj,'foo[1][2]')
getDeepVal(obj,"foo['bar'].baz")
getDeepVal(obj,"foo['bar']['baz']")
getDeepVal(obj,"foo.bar.0.baz[1]['2']['w'].aaa[\"f\"].bb")

答案 18 :(得分:1)

虽然减少是好的,但我很惊讶没有人用于每个:

function() { ancrecupid(); calculerIMC();....

Test

答案 19 :(得分:1)

基于Alnitak的answer

我将polyfill包裹在一张支票中,并将功能简化为单链式简化。

if (Object.byPath === undefined) {
  Object.byPath = (obj, path) => path
    .replace(/\[(\w+)\]/g, '.$1')
    .replace(/^\./, '')
    .split(/\./g)
    .reduce((ref, key) => key in ref ? ref[key] : ref, obj)
}

const data = {
  foo: {
    bar: [{
      baz: 1
    }]
  }
}

console.log(Object.byPath(data, 'foo.bar[0].baz'))

答案 20 :(得分:1)

受@webjay的回答启发: https://stackoverflow.com/a/46008856/4110122

我创建了此函数,可以使用它获取/设置/取消设置对象中的任何值

function Object_Manager(obj, Path, value, Action) 
{
    try
    {
        if(Array.isArray(Path) == false)
        {
            Path = [Path];
        }

        let level = 0;
        var Return_Value;
        Path.reduce((a, b)=>{
            level++;
            if (level === Path.length)
            {
                if(Action === 'Set')
                {
                    a[b] = value;
                    return value;
                }
                else if(Action === 'Get')
                {
                    Return_Value = a[b];
                }
                else if(Action === 'Unset')
                {
                    delete a[b];
                }
            } 
            else 
            {
                return a[b];
            }
        }, obj);
        return Return_Value;
    }

    catch(err)
    {
        console.error(err);
        return obj;
    }
}

要使用它:

 // Set
 Object_Manager(Obj,[Level1,Level2,Level3],New_Value, 'Set');

 // Get
 Object_Manager(Obj,[Level1,Level2,Level3],'', 'Get');

 // Unset
 Object_Manager(Obj,[Level1,Level2,Level3],'', 'Unset');

答案 21 :(得分:0)

反应示例-使用lodash

从性能的角度来看,这可能不是最有效的方法,但是,如果您的应用程序过于单一,那么可以肯定会节省一些时间。尤其是当您将状态数据格式与API后端紧密耦合时。

   import set from "lodash/set";  // More efficient import

    class UserProfile extends Component {

      constructor(props){
        super(props);

        this.state = {
          user: {
            account: {
              id: "",
              email: "",
              first_name: ""
            }
          }
        }
      }

       /**
       * Updates the state based on the form input
       * 
       * @param {FormUpdate} event 
       */
      userAccountFormHook(event) {
        // https://lodash.com/docs#get
        // https://lodash.com/docs#set
        const { name, value } = event.target;
        let current_state = this.state
        set(current_state, name, value)  // Magic happens here
        this.setState(current_state);
      }

    render() {
        return (
          <CustomFormInput
            label: "First Name"
            type: "text"
            placeholder: "First Name"
            name: "user.account.first_name"
            onChange: {this.userAccountFormHook}
            value: {this.state.user.account.first_name}

          />
      )
  }
}

答案 22 :(得分:0)

您可以使用ramda库。

学习ramda还可以帮助您轻松处理不可变的对象。


var obj = {
  a:{
    b: {
      c:[100,101,{
        d: 1000
      }]
    }
  }
};


var lens = R.lensPath('a.b.c.2.d'.split('.'));
var result = R.view(lens, obj);


https://codepen.io/ghominejad/pen/BayJZOQ

答案 23 :(得分:0)

可以使用数组代替字符串来解决嵌套对象和数组,例如:["my_field", "another_field", 0, "last_field", 10]

这是一个基于此数组表示更改字段的示例。我在react.js中使用类似的东西来控制输入字段,这些字段可以改变嵌套结构的状态。

let state = {
        test: "test_value",
        nested: {
            level1: "level1 value"
        },
        arr: [1, 2, 3],
        nested_arr: {
            arr: ["buh", "bah", "foo"]
        }
    }

function handleChange(value, fields) {
    let update_field = state;
    for(var i = 0; i < fields.length - 1; i++){
        update_field = update_field[fields[i]];
    }
    update_field[fields[fields.length-1]] = value;
}

handleChange("update", ["test"]);
handleChange("update_nested", ["nested","level1"]);
handleChange(100, ["arr",0]);
handleChange('changed_foo', ["nested_arr", "arr", 3]);
console.log(state);

答案 24 :(得分:0)

AngularJS具有$scope.$eval

使用AngularJS,可以使用$scope.$eval方法访问嵌套对象:

$scope.someObject = someObject;
console.log( $scope.$eval("someObject.part3[0].name") ); //Part 3A

有关更多信息,请参见

演示

angular.module("app",[])
.run(function($rootScope) {
     $rootScope.someObject = {
         'part2' : {
              'name': 'Part 2',
              'size': '15',
              'qty' : '60'
         },
         'part3' : [{
              'name': 'Part 3A',
              'size': '10',
              'qty' : '20'
         },{
              name: 'Part 3B'           
         }]
     };
     console.log(
         "part3[0].name =",
         $rootScope.$eval("someObject.part3[0].name")
    );
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"
</body>

答案 25 :(得分:0)

请注意,以下内容不适用于所有有效的unicode属性名称(但据我所知,其他任何答案都无效)。

const PATTERN = /[\^|\[|\.]([$|\w]+)/gu

function propValue(o, s) {
    const names = []
    for(let [, name] of [...s.matchAll(PATTERN)]) 
        names.push(name)
    return names.reduce((p, propName) => {
        if(!p.hasOwnProperty(propName)) 
            throw 'invalid property name'
        return p[propName]
    }, o)
}

let path = 'myObject.1._property2[0][0].$property3'
let o = {
    1: {
        _property2: [
            [{
                $property3: 'Hello World'
            }]
        ]
    }
}
console.log(propValue(o, path)) // 'Hello World'

答案 26 :(得分:0)

使用 object-scan 这成为一个单行。但更重要的是,此解决方案考虑了性能:

  • 输入在搜索过程中遍历一次(即使查询多个键)
  • 解析只在初始化时发生一次(以防查询多个对象)
  • 允许使用 * 扩展语法

// const objectScan = require('object-scan');

const someObject = { part1: { name: 'Part 1', size: '20', qty: '50' }, part2: { name: 'Part 2', size: '15', qty: '60' }, part3: [{ name: 'Part 3A', size: '10', qty: '20' }, { name: 'Part 3B', size: '5', qty: '20' }, { name: 'Part 3C', size: '7.5', qty: '20' }] };

const get = (haystack, needle) => objectScan([needle], { rtn: 'value', abort: true })(haystack);

console.log(get(someObject, 'part1.name'));
// => Part 1
console.log(get(someObject, 'part2.qty'));
// => 60
console.log(get(someObject, 'part3[0].name'));
// => Part 3A

const getAll = (haystack, ...needles) => objectScan(needles, { reverse: false, rtn: 'entry', joined: true })(haystack);

console.log(getAll(someObject, 'part1.name', 'part2.qty', 'part3[0].name'));
/* =>
[ [ 'part1.name', 'Part 1' ],
  [ 'part2.qty', '60' ],
  [ 'part3[0].name', 'Part 3A' ] ]
 */

console.log(getAll(someObject, 'part1.*'));
/* =>
[ [ 'part1.name', 'Part 1' ],
  [ 'part1.size', '20' ],
  [ 'part1.qty', '50' ] ]
 */
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

免责声明:我是object-scan

的作者

答案 27 :(得分:0)

这可以通过将逻辑拆分为三个独立的函数来简化:

const isVal = a => a != null; // everything except undefined + null

const prop = prop => obj => {
    if (isVal(obj)) {
        const value = obj[prop];
        if (isVal(value)) return value;
        else return undefined;
    } else return undefined;
};

const path = paths => obj => {
    const pathList = typeof paths === 'string' ? paths.split('.') : paths;
    return pathList.reduce((value, key) => prop(key)(value), obj);
};

此变体支持:

  • 传递数组或字符串参数
  • 在调用和执行期间处理 undefined
  • 独立测试每个功能
  • 独立使用每个功能

答案 28 :(得分:0)

与其尝试模拟 JS 语法,您将不得不花费大量的计算解析,或者只是出错/忘记诸如一堆这些答案(带有 . 的键,有人吗?),只需使用一组键即可。

如果您需要使用单个字符串,只需 JSONify 即可。
此方法的另一个改进是您可以删除/设置根级别对象。

function resolve(obj, path) {
    let root = obj = [obj];
    path = [0, ...path];
    while (path.length > 1)
        obj = obj[path.shift()];
    return [obj, path[0], root];
}
Object.get = (obj, path) => {
    let [parent, key] = resolve(obj, path);
    return parent[key];
};
Object.del = (obj, path) => {
    let [parent, key, root] = resolve(obj, path);
    delete parent[key];
    return root[0];
};
Object.set = (obj, path, value) => {
    let [parent, key, root] = resolve(obj, path);
    parent[key] = value;
    return root[0];
};

演示:
demonstration

除非您的路径可能为空(操作根对象),否则 bob = /.set(.del( 不是必需的。
我证明我没有通过使用 steve 保留对原始对象的引用并在第一个 bob == steve //true

之后检查 .set( 来克隆对象

答案 29 :(得分:0)

扩展Mohamad Hamouday'答案将填写缺少的键

function Object_Manager(obj, Path, value, Action, strict) 
{
    try
    {
        if(Array.isArray(Path) == false)
        {
            Path = [Path];
        }

        let level = 0;
        var Return_Value;
        Path.reduce((a, b)=>{
            console.log(level,':',a, '|||',b)
            if (!strict){
              if (!(b in a)) a[b] = {}
            }


            level++;
            if (level === Path.length)
            {
                if(Action === 'Set')
                {
                    a[b] = value;
                    return value;
                }
                else if(Action === 'Get')
                {
                    Return_Value = a[b];
                }
                else if(Action === 'Unset')
                {
                    delete a[b];
                }
            } 
            else 
            {
                return a[b];
            }
        }, obj);
        return Return_Value;
    }

    catch(err)
    {
        console.error(err);
        return obj;
    }
}

示例


obja = {
  "a": {
    "b":"nom"
  }
}

// Set
path = "c.b" // Path does not exist
Object_Manager(obja,path.split('.'), 'test_new_val', 'Set', false);

// Expected Output: Object { a: Object { b: "nom" }, c: Object { b: "test_new_value" } }

答案 30 :(得分:0)

我正在与React合作开发在线商店。我试图更改复制状态对象中的值,以在提交时更新其原始状态。 上面的示例对我而言并不奏效,因为它们大多数会使复制对象的结构发生变异。我找到了用于访问和更改深层嵌套对象属性的值的函数的工作示例:https://lowrey.me/create-an-object-by-path-in-javascript-2/这里是:

const createPath = (obj, path, value = null) => {
  path = typeof path === 'string' ? path.split('.') : path;
  let current = obj;
  while (path.length > 1) {
    const [head, ...tail] = path;
    path = tail;
    if (current[head] === undefined) {
      current[head] = {};
    }
    current = current[head];
  }
  current[path[0]] = value;
  return obj;
};

答案 31 :(得分:0)

使用Underscore的{​​{1}}或property

propertyOf
var test = {
  foo: {
    bar: {
      baz: 'hello'
    }
  }
}
var string = 'foo.bar.baz';


// document.write(_.propertyOf(test)(string.split('.')))

document.write(_.property(string.split('.'))(test));

祝你好运...

答案 32 :(得分:0)

&#13;
&#13;
class App extends Component {

  constructor(props) {
    super(props);
    this.state = { 
      isLoggedIn: Cookies.get('isLoggedIn')
    }
  }

  componentWillMount() {
    if (this.state.isLoggedIn) {
      Account.get().then(({data}) => {
        this.setState({ user: data })
        window.me = data
      }).catch(err => handleErrors(this, err))
    }
  }

  render() {
    if (!this.state.isLoggedIn) {
      return <LoginModal setLoggedIn={(data) => {
        Cookies.set('isLoggedIn', true);
        this.setState({ user: data, isLoggedIn: true });
        window.me = data;
      }}/>
    }
    if (!this.state.user) {
      return <Loading/>
    }
    return (
      <div>
        <Router>
          <ShortcutHandler>
            <TopBar user={this.state.user}/>
            <div className="ContentPane d-flex">
              <SideBar />
              <div className="Content">
                <Route exact path="/" component={Dashboard} />
                <Route path="/venues" component={Venues} />
                <Route path="/trainers" component={TrainersList} />
                <Route path="/classes" component={Coaching} />
                <Route path="/plans" component={Coaching} />
                <Route path="/customers/:id(\d+)?" component={PlayersList} />
                <Route path="/enrollments/:id(\d+)?" component={Subscriptions} />
                <Route path="/invoices/:id(\d+)?" component={Invoices} />
                <Route path="/payments/:id(\d+)?" component={PaymentsList} />
                <Route path="/analytics" component={ComingSoon} />
                <Route path="/settings" component={Settings} />
                <Route path="/logout" component={logout.bind(this)} />
              </div>
            </div>
          </ShortcutHandler>
        </Router>
      </div>
    );
  }
}

export default App;

export const logout = () => {
  Cookies.remove('isLoggedIn');
  window.me = undefined;
  window.currentOrg = undefined;
  window.location.pathname = '/';
  return null;
}
&#13;
&#13;
&#13;

答案 33 :(得分:0)

根据之前的回答,我创建了一个也可以处理括号的函数。但由于分裂,它们内部没有任何点。

function get(obj, str) {
  return str.split(/\.|\[/g).map(function(crumb) {
    return crumb.replace(/\]$/, '').trim().replace(/^(["'])((?:(?!\1)[^\\]|\\.)*?)\1$/, (match, quote, str) => str.replace(/\\(\\)?/g, "$1"));
  }).reduce(function(obj, prop) {
    return obj ? obj[prop] : undefined;
  }, obj);
}

答案 34 :(得分:0)

此处的解决方案仅用于访问深层嵌套的密钥。我需要一个用于访问,添加,修改和删除密钥。这就是我想出的:

var deepAccessObject = function(object, path_to_key, type_of_function, value){
    switch(type_of_function){
        //Add key/modify key
        case 0: 
            if(path_to_key.length === 1){
                if(value)
                    object[path_to_key[0]] = value;
                return object[path_to_key[0]];
            }else{
                if(object[path_to_key[0]])
                    return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
                else
                    object[path_to_key[0]] = {};
            }
            break;
        //delete key
        case 1:
            if(path_to_key.length === 1){
                delete object[path_to_key[0]];
                return true;
            }else{
                if(object[path_to_key[0]])
                    return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
                else
                    return false;
            }
            break;
        default:
            console.log("Wrong type of function");
    }
};
  • path_to_key:数组中的路径。您可以使用string_path.split(".")
  • 替换它
  • type_of_function:0表示访问(不传递任何值到value),0表示添加和修改。 1表示删除。

答案 35 :(得分:0)

最近遇到了同样的问题并成功使用了https://npmjs.org/package/tea-properties set嵌套对象/数组:

得到:

var o = {
  prop: {
    arr: [
      {foo: 'bar'}
    ]
  }
};

var properties = require('tea-properties');
var value = properties.get(o, 'prop.arr[0].foo');

assert(value, 'bar'); // true

组:

var o = {};

var properties = require('tea-properties');
properties.set(o, 'prop.arr[0].foo', 'bar');

assert(o.prop.arr[0].foo, 'bar'); // true

答案 36 :(得分:0)

如果您需要在编码时不知道它而访问不同的嵌套密钥(解决它们将很容易),您可以使用数组符号访问器:

var part1name = someObject['part1']['name'];
var part2quantity = someObject['part2']['qty'];
var part3name1 =  someObject['part3'][0]['name'];

它们等同于点符号访问器,并且可能在运行时有所不同,例如:

var part = 'part1';
var property = 'name';

var part1name = someObject[part][property];

相当于

var part1name = someObject['part1']['name'];

var part1name = someObject.part1.name;

我希望这能解决你的问题...

修改

我不会使用字符串来保存某种xpath 查询来访问对象值。 因为你必须调用一个函数来解析查询并检索值,我将遵循另一条路径(不是:

var part1name = function(){ return this.part1.name; }
var part2quantity = function() { return this['part2']['qty']; }
var part3name1 =  function() { return this.part3[0]['name'];}

// usage: part1name.apply(someObject);

或者,如果您对 apply 方法感到不安

var part1name = function(obj){ return obj.part1.name; }
var part2quantity = function(obj) { return obj['part2']['qty']; }
var part3name1 =  function(obj) { return obj.part3[0]['name'];}

// usage: part1name(someObject);

函数更短,更清晰,解释器会检查它们是否存在语法错误等等。

顺便说一下,我觉得在正确的时间做出简单的任务就足够了......

答案 37 :(得分:-1)

从@Alnitak答案开始,我构建了此源,该源下载了一个实际的.JSON文件并进行处理,为每个步骤打印到控制台说明字符串,并在传递错误密钥的情况下提供了更多详细信息:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <script>
function retrieveURL(url) {
        var client = new XMLHttpRequest();
        prefix = "https://cors-anywhere.herokuapp.com/"
        client.open('GET', prefix + url);
        client.responseType = 'text';
        client.onload = function() {
            response = client.response; // Load remote response.
            console.log("Response received.");
            parsedJSON  = JSON.parse(response);
            console.log(parsedJSON);
            console.log(JSONitemByPath(parsedJSON,"geometry[6].obs[3].latituade"));
            return response;
        };
        try {
            client.send();
        } catch(e) {
            console.log("NETWORK ERROR!");
            console.log(e);
        }
}



function JSONitemByPath(o, s) {
    structure = "";
    originalString = s;
    console.log("Received string: ", s);
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    console.log("Converted to   : ", s);
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');

    console.log("Single keys to parse: ",a);

    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
            console.log("object." + structure +  a[i], o);
            structure +=  a[i] + ".";
        } else {
            console.log("ERROR: wrong path passed: ", originalString);
            console.log("       Last working level: ", structure.substr(0,structure.length-1));
            console.log("       Contents: ", o);
            console.log("       Available/passed key: ");
            Object.keys(o).forEach((prop)=> console.log("       "+prop +"/" + k));
            return;
        }
    }
    return o;
}


function main() {
    rawJSON = retrieveURL("http://haya2now.jp/data/data.json");
}

</script>
  </head>
  <body onload="main()">
  </body>
</html>

输出示例:

Response received.
json-querier.html:17 {geometry: Array(7), error: Array(0), status: {…}}
json-querier.html:34 Received string:  geometry[6].obs[3].latituade
json-querier.html:36 Converted to   :  geometry.6.obs.3.latituade
json-querier.html:40 Single keys to parse:  (5) ["geometry", "6", "obs", "3", "latituade"]
json-querier.html:46 object.geometry (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
json-querier.html:46 object.geometry.6 {hayabusa2: {…}, earth: {…}, obs: Array(6), TT: 2458816.04973593, ryugu: {…}, …}
json-querier.html:46 object.geometry.6.obs (6) [{…}, {…}, {…}, {…}, {…}, {…}]
json-querier.html:46 object.geometry.6.obs.3 {longitude: 148.98, hayabusa2: {…}, sun: {…}, name: "DSS-43", latitude: -35.4, …}
json-querier.html:49 ERROR: wrong path passed:  geometry[6].obs[3].latituade
json-querier.html:50        Last working level:  geometry.6.obs.3
json-querier.html:51        Contents:  {longitude: 148.98, hayabusa2: {…}, sun: {…}, name: "DSS-43", latitude: -35.4, …}
json-querier.html:52        Available/passed key: 
json-querier.html:53        longitude/latituade
json-querier.html:53        hayabusa2/latituade
json-querier.html:53        sun/latituade
json-querier.html:53        name/latituade
json-querier.html:53        latitude/latituade
json-querier.html:53        altitude/latituade
json-querier.html:18 undefined

答案 38 :(得分:-1)

建立Alnitak的答案:

if(!Object.prototype.byString){
  //NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
  var _o = o || this;
      s = s.replace(/\[(\w+)\]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
      s = s.replace(/^\./, ''); // STRIP A LEADING DOT
      var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
      for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
          var k = a[i];
          if (k in _o) {//LOOP THROUGH OBJECT KEYS
              if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
                if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
                  if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
                    _o[k] = v;
                  }
                }
                _o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
              }
          } else {
              return;
          }
      }
      return _o;
  };

}

这也允许你设置一个值!

我已经创建了npm packagegithub

答案 39 :(得分:-1)

这个解决方案怎么样:

setJsonValue: function (json, field, val) {
  if (field !== undefined){
    try {
      eval("json." + field + " = val");
    }
    catch(e){
      ;
    }
  }  
}

这一个,获得:

getJsonValue: function (json, field){
  var value = undefined;
  if (field !== undefined) {
    try {
      eval("value = json." + field);
    } 
    catch(e){
      ;
    }
  }
  return value;
};

可能有些人会认为它们不安全,但它们必须比解析字符串快得多。