简体   繁体   English

将key:value复制到数组Javascript的对象元素中

[英]Copy key:value to object elements of an array Javascript

This is a simple test of javascript knowledge that I seem to be lacking. 这是对我似乎缺少的javascript知识的简单测试。 I'm basically writing a query front end for monogdb, it's almost done apart from one little piece. 我基本上是在为monogdb写一个查询前端,它几乎完成了一件小事。 Queries are built by clicking elements and most of the logic works. 查询是通过单击元素构建的,大多数逻辑工作正常。 I'm stuck on building an $and query. 我坚持建立$and查询。

I have a flat object like this: 我有一个像这样的扁平物体:

obj1: {
    prop1: 'val1'
}

These key values are added dynamically when the user clicks on a list-item and enters a custom value. 当用户单击列表项并输入自定义值时,将动态添加这些键值。 When the user clicks 2 or more items from the list-items I would like for my object to end up like this: 当用户单击列表项中的2个或更多项时,我希望对象最终像这样:

obj1: {
  $and: [
  {prop1: 'val1'},
  {prop2: 'val2'},
  {prop3: 'val3'}
  ]
}

Where all the original key value strings are wrapped in {} and become elements to an $and array. 所有原始键值字符串都包装在{}并成为$and数组的元素。

I can get the first part working ie turning the key values into objects. 我可以使第一部分工作,即将键值转换为对象。 And I can get the second part, injecting an $and array and feeding it some kind of object but I can't get the two to work together consistently. 我可以得到第二部分,注入$and数组并为其提供某种对象,但是我无法使两者始终如一地协同工作。

It requires taking the value already in obj1 , making an object out of it and pushing it into an array. 它需要获取obj1已经存在的值, obj1创建一个对象并将其推入数组。 Injecting that array into obj1 , and then removing the old key value from obj1 . 将该数组注入obj1 ,然后从obj1删除旧键值。

This is as far as I've got: 据我所知:

var add = []
var newElementObject= {}

for (var prop in obj1) {
    newElementObject = {};
    newElementObject[prop] = "custom value entered by user";
    delete obj1[prop]
    add.push(newElementObject);
}

obj1.$and = add;

It works, once. 它可以一次。 I get the structure I'm looking for but when I try to add more items to the $and array something craps out. 我得到了我要寻找的结构,但是当我尝试向$and数组中添加更多项目时,一些东西就消失了。 The second obj updates and the first just sits there saying: 第二个obj更新,第一个obj坐在那里说:

{$and : "custom value entered by user"}

I've been staring at this for too long. 我盯着这个看了太久了。

Try 尝试

var newElementObject = {};
obj1.$add = obj1.$add || []; //keep the old array or make a new one

for (var prop in obj1) {
    if (!obj1.hasOwnProperty(prop) || prop == '$add') { continue; }
    newElementObject = {};
    newElementObject[prop] = "custom value entered by user";
    delete obj1[prop]
    obj1.$add.push(newElementObject);
}

That way you're not going to overwrite the old array reference if you run this code twice on the same object, which is what it sounds like your problem is. 这样,如果您在同一对象上运行两次此代码,就不会覆盖旧的数组引用,这听起来像是您的问题所在。

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

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