【问题标题】:How to pass multiple object attributes as parameter? [duplicate]如何将多个对象属性作为参数传递? [复制]
【发布时间】:2020-06-09 12:39:21
【问题描述】:

我们以这个对象为例:

var obj = {a: {b: {c: 'result'}}}

我知道我可以得到c的值,这样做:

console.log(obj.a.b.c) // 'result'

或者这个:

console.log(obj['a']['b']['c'])

但是如何在函数中将 obj 和列作为参数传递给 c 的值?

function func(obj, attributes) {
   return obj[attributes]
}

console.log(func(obj, a.b.c)) // how to make this work
console.log(func(obj, ['a']['b']['c'])) // or this

【问题讨论】:

标签: javascript


【解决方案1】:

您可以将attributes 传递为string,如'a.b.c'。然后将其拆分并使用reduce 获得所需的值。

在下面测试一下。

var obj = {a: {b: {c: 'result'}}}
function func(obj, attributes) {
  return attributes.split('.').reduce((x, a) => x[a], obj);
}

console.log(func(obj, 'a.b.c'));
console.log(func(obj, 'a.b'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2011-06-12
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多