简体   繁体   English

如何编辑JavaScript对象

[英]How to edit a javascript object

I'm new to Javascript and I have an object that printed to console gives this : 我是Java语言的新手,并且有一个打印到控制台的对象给出了以下内容:

Object
    mots[4]:"unique"

I would like to edit it to get : 我想对其进行编辑以获取:

Object
    mots[4].lettre:"unique"

I tried using stringify, split and splice but that didn't work. 我尝试使用stringify,split和splice,但这没有用。 So what is the 'cleanest' way to do that? 那么什么是“最干净”的方法呢?

mots[4] = { lettre : "unique" }

or generically.. 或一般而言。

mots[i] = { lettre : mots[i] }

or for each value in the array you can do.. 或您可以对数组中的每个值进行操作。

mots = mots.map(function(x) { return { lettre : x }; });

This will convert every element of the array to be an object with the property lettre with the value of the original element. 这会将数组的每个元素转换为具有lettre属性和原始元素值的对象。 Learn more about the map function . 了解有关地图功能的更多信息。

 var mots = ['This', 'answer', 'is', 'very', 'unique']; console.log('Before:'); console.log(mots); console.log('mots[4] : ' + mots[4]); mots = mots.map(function(x) { return { lettre : x }; }); console.log('After:'); console.log(mots); console.log('mots[4].lettre : ' + mots[4].lettre); 

You have to assign to it an object. 您必须为其分配一个对象。

var a=4;
mots[a]={letter:"unique"};

You can access it using bracket notation. 您可以使用方bracket符号来访问它。

console.log(mots[a]["lettre"]).

 var mots=[]; for(i=0;i<5;i++){ mots[i]=i; } a=4; console.log(mots); mots[a]={letter:"unique"}; console.log(mots[a]["letter"]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM