操作对象属性并重新分配的快捷方式

时间:2019-01-02 16:16:31

标签: javascript

我有一个深层嵌套的对象,我想操纵它的值并重新分配它。除了重新将其全部写出或将其分配给变量之外,还有其他简便的方法吗?

Allocating 32 buffers of 2500 samples each
Traceback (most recent call last):
  File "p.py", line 79, in <module>
    dic='E:\Sphinx 2\pocketsphinx\\bin\Release\Win32\8749.dict'
  File "C:\Users\Shahiryar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pocketsphinx\__init__.py", line 208, in __init__
    super(LiveSpeech, self).__init__(**kwargs)
  File "C:\Users\Shahiryar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pocketsphinx\__init__.py", line 90, in __init__
    super(Pocketsphinx, self).__init__(config)
  File "C:\Users\Shahiryar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pocketsphinx\pocketsphinx.py", line 272, in __init__
    this = _pocketsphinx.new_Decoder(*args)
RuntimeError: new_Decoder returned -1

看起来很丑吗?像这样:

createStops[idx]['place']['create'][stop][key][value] = createStops[idx]['place']['create'][stop][key][value].toString()

但内置JS。

编辑:就我而言,这是一个数字,如果也适合您,请查看@MarkMeyer答案。

6 个答案:

答案 0 :(得分:3)

不,没有。

分配新值需要分配。

字符串是不可变的,因此您不能将现有值直接转换为字符串。

答案 1 :(得分:3)

给出一个数字值,如果您只是想将其作为字符串,则可以使用赋值运算符将其强制为字符串:

let o = {
    akey: {
        akey:{
            value: 15
        }
    }
}

o.akey.akey.value += ''
console.log(o)

答案 2 :(得分:0)

不, 需要使用相同的索引来存储值

答案 3 :(得分:0)

尽管不可能像@Quentin提到的那样,您可以在对象中定义自定义getter,例如:

var foo = {
  a: 5,
  b: 6,
  get c () {
    return this.b.toString()+' text'
  }
};

console.log(foo.c);

在语义上格式化值时,您不会重新分配值。为了格式化您的值,您正在变异您的初始对象。如果您不假装出于格式化目的而修改对象,那将很好用。

答案 4 :(得分:0)

您没有像这样使用的集成功能,但是您可以使用自己的一些实用功能来帮助您管理分配并减少口头表达。

SPOIL :最终用途类似于

// call the function to do +1 at the specified key
executeFunctionAtKey(
  // The object to change the value on
  createStops,

  // The path
  `${idx}.place.create.${stop}.${key}.${value}`,

  // The thing to do
  (x) => x + 1,
);

const createStops = {
  idx: {
    place: {
      create: {
        stop: {
          key: {
            value: 5,
          },
        },
      },
    },
  },
};

const idx = 'idx';
const stop = 'stop';
const key = 'key';
const value = 'value';

// Function that go to the specified key and
// execute a function on it.
// The new value is the result of the func
// You can do your toString there, or anything else
function executeFunctionAtKey(obj, path, func) {
  const keys = path.split('.');

  if (keys.length === 1) {
    obj[path] = func(obj[key]);

    return obj;
  }

  const lastPtr = keys.slice(0, keys.length - 1).reduce((tmp, x) => tmp[x], obj);

  lastPtr[keys[keys.length - 1]] = func(lastPtr[keys[keys.length - 1]]);

  return obj;
}

// call the function to do +1 at the specified key
executeFunctionAtKey(
  // The object to change the value on
  createStops,

  // The path
  `${idx}.place.create.${stop}.${key}.${value}`,

  // The thing to do
  (x) => x + 1,
);

console.log(createStops);



toStringNumber的{​​{1}}为例

String

答案 5 :(得分:0)

理论上,您可以构建一个接受对象,路径和属性的函数。

这会降低代码的可读性,所以我建议使用普通分配。但是,如果需要,请查看下面的代码段:

//
function setProp(object, path, val) {
    var parts = path.split("/").filter(function (p) { return p.length > 0; });
    var pathIndex = 0;
    var currentTarget = object;
    while (pathIndex < parts.length - 1) {
        currentTarget = currentTarget[parts[pathIndex]];
        pathIndex++;
    }
    if (val instanceof Function) {
        currentTarget[parts[pathIndex]] = val(currentTarget[parts[pathIndex]]);
    }
    else {
        currentTarget[parts[pathIndex]] = val;
    }
    return object;
}
var createStops = {
    idx: {
        place: {
            create: {
                stop: {
                    key: {
                        value: 5
                    }
                }
            }
        }
    }
};
function toString(p) { return p.toString(); }
console.log(JSON.stringify(createStops, null, 4));
setProp(createStops, 'idx/place/create/stop/key/value', toString);
console.log(JSON.stringify(createStops, null, 4));

更新1

允许传递函数,并为片段使用OP JSON结构

相关问题