Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在不覆盖前一个值的情况下将多个值设置为同一个键?_Javascript_Arrays_Object_Ecmascript 6 - Fatal编程技术网

Javascript 如何在不覆盖前一个值的情况下将多个值设置为同一个键?

Javascript 如何在不覆盖前一个值的情况下将多个值设置为同一个键?,javascript,arrays,object,ecmascript-6,Javascript,Arrays,Object,Ecmascript 6,基本上,我希望能够为一个键添加多个值,方法是将所述值放入一个数组中,并将其设置为我的主对象以供以后访问。我怎样才能最好地着手做这件事?这是如此令人沮丧,我感到沮丧,并问自己为什么我曾经认为我可以这样做 let mainObj = {} const func = (str, obj) => { mainObj[str] = [obj] } func('str1', {content: 'content1' } ) func('str2', {content: 'content2'

基本上,我希望能够为一个键添加多个值,方法是将所述值放入一个数组中,并将其设置为我的主对象以供以后访问。我怎样才能最好地着手做这件事?这是如此令人沮丧,我感到沮丧,并问自己为什么我曾经认为我可以这样做

let mainObj = {}


const func = (str, obj) => {
  mainObj[str] = [obj]
}

func('str1', {content: 'content1' } )
func('str2', {content: 'content2' } )
func('str2', {content: 'content3' } )

console.log(mainObj)

//instead of this:
{ str1: [ { content: 'content1' } ],
  str2: [ { content: 'content3' } ] }


//I want this:
{ 
  str1: [ { content: 'content1' } ],
  str2: [ {content: 'content2' }, { content: 'content3' } ]
}

只需按如下方式制作一个数组:

const func=(str,obj)=>{
mainObj[str]=(mainObj[str]| | |[])。concat([obj])
}

只需将其做成如下数组:

const func=(str,obj)=>{
mainObj[str]=(mainObj[str]| | |[])。concat([obj])
}

您应该首先检查是否已经存在使用该字符串键的数组

如果是,则将其推送到该阵列,而不是替换为新阵列

如果没有,则执行您正在执行的操作M使用该键创建一个数组
let mainObj={}
常量func=(str,obj)=>{
if(mainObj[str]){
mainObj[str].推送(obj)
}否则{
mainObj[str]=[obj]
}
}
func('str1',{content:'content1'})
func('str2',{content:'content2'})
func('str2',{content:'content3'})
控制台日志(mainObj)

//与此相反:
您应该首先检查是否已经存在具有该字符串键的数组

如果是,则将其推送到该阵列,而不是替换为新阵列

如果没有,则执行您正在执行的操作M使用该键创建一个数组
let mainObj={}
常量func=(str,obj)=>{
if(mainObj[str]){
mainObj[str].推送(obj)
}否则{
mainObj[str]=[obj]
}
}
func('str1',{content:'content1'})
func('str2',{content:'content2'})
func('str2',{content:'content3'})
控制台日志(mainObj)

//与此相反:
您应该推送到元素上,而不是覆盖它

let mainObj={}
常量func=(str,obj)=>{
如果(!mainObj[str]){
mainObj[str]=[];
}
mainObj[str].推送(obj);
}
func('str1'{
内容:“content1”
})
func('str2'{
内容:“内容2”
})
func('str2'{
内容:“内容3”
})

console.log(mainObj)
您应该推送到元素上,而不是覆盖它

let mainObj={}
常量func=(str,obj)=>{
如果(!mainObj[str]){
mainObj[str]=[];
}
mainObj[str].推送(obj);
}
func('str1'{
内容:“content1”
})
func('str2'{
内容:“内容2”
})
func('str2'{
内容:“内容3”
})

console.log(mainObj)
非常感谢您!我需要放松,有计划地思考。非常感谢!我需要放松,有计划地思考