简体   繁体   English

如何在javascript中将数组与对象合并

[英]How can I merge an Array with an object in javascript

I'm having an array of object 我有一个对象数组

   var todos=  [
        {
            id: 1,
            name: test,
            description: test
        }
    ]

How can I insert an object with properties stored in different variable say 我如何插入具有存储在不同变量中的属性的对象,例如

var newTodos={id:2,name:test2,description:test2,purpose:NA} 

so that the final arrray looks like var todos= 这样最终的错误看起来就像var todos =

 [
    {
        id: 1,
        name: test,
        description: test
    },
    id: 2,
    name: test2,
    description: test2,
    purpose: NA
]
var todos=  [
        {
            id: 1,
            name: test,
            description: test
        }
    ]  
var newTodos={id:2,name:test2,description:test2,purpose:NA};
todos.push(newTodos);

The answer you accepted is the right answer to the wrong question. 您接受的答案是对错误问题的正确答案。

If you really want to add the properties of newTodos (which is misnamed; it is just a single todo) then you can do what the answer says, or more easily, just do 如果您确实要添加newTodos的属性(名称不正确;它只是一个待办事项),那么您可以按照答案所说的做,或更简单地,只需执行

$.extend     (todos, newTodos);
_.extend     (todos, newTodos);
Object.assign(todos, newTodos);

or use your other favorite property merging utility. 或使用您其他喜欢的属性合并实用程序。

However, I cannot imagine what you are going to usefully do with such a mutant object, which is an array with a single element which is a todo, and now is sort of a todo itself with the todo properties directly on it. 但是,我无法想象您将如何有效地使用这种突变对象,该突变对象是一个具有单个元素的数组,该元素是一个待办事项,而现在是某种待办事项本身,直接具有待办事项属性。

I'm guessing that what you want to do is add another todo to your array of todos, in which case as others have suggested you can just push it. 我猜想您想做的就是在待办事项数组中添加另一个待办事项,在这种情况下,正如其他人所建议的,您可以pushpush

todos.push(newTodos)

If you actually mean newTodos to be an array of todos, as its name suggests, in other words, if its format is actually 如果实际上是说newTodos是一个newTodos数组,顾名思义,换句话说,其格式实际上是

var newTodos = [ {id:2,name:test2,description:test2,purpose:NA}, ... ];

Then to add it to todos you would concatenate: 然后将其添加到待办事项中,可以串联起来:

todos = todos.concat(newTodos);

This is how you do it: 这是您的操作方式:

for (var index in newTodos) {
    todos[index] = newTodos[index];
}

You can check the values of your array like this: 您可以像这样检查数组的值:

for (var index in todos) {
   console.log(index + ": " + todos[index]);
}

EDIT: In conform with the asked fiddle , I add the fiddle and code: 编辑:按照要求的小提琴 ,我添加小提琴和代码:

<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>

  <script type="text/javascript" src="/js/lib/dummy.js"></script>




  <link rel="stylesheet" type="text/css" href="/css/result-light.css">

  <style type="text/css">

  </style>



<script type="text/javascript">//<![CDATA[ 
var VanillaRunOnDomReady = function() {
var todos=  [
    {
        id: 1,
        name: 'test',
        description: 'test'
    }
];
var newTodos={id:2,name:'test2',description:'test2',purpose:'NA'};
for (var index in newTodos) {
    todos[index] = newTodos[index];
}
var output = "";
for (var index in todos) {
    if (typeof todos[index] === "object") {
        output += index + ": {";
        var first = true;
        for (var innerIndex in todos[index]) {
            if (!first) {
                output += ", ";
            } else {
                first = false;
            }
            output += innerIndex + ": " + todos[index][innerIndex];
        }
        output += "}<br>";
    } else {
        output += index + ": " + todos[index] + "<br>";
    }
}
document.getElementById("output").innerHTML = output;
}

var alreadyrunflag = 0;

if (document.addEventListener)
    document.addEventListener("DOMContentLoaded", function(){
        alreadyrunflag=1; 
        VanillaRunOnDomReady();
    }, false);
else if (document.all && !window.opera) {
    document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
    var contentloadtag = document.getElementById("contentloadtag")
    contentloadtag.onreadystatechange=function(){
        if (this.readyState=="complete"){
            alreadyrunflag=1;
            VanillaRunOnDomReady();
        }
    }
}

window.onload = function(){
  setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}//]]>  
</script>
</head>
<body>
    <div id="output">a</div>
</body></html>

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

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