简体   繁体   English

根据JavaScript中的条件将对象拆分为对象数组

[英]Split an object into array of objects based on a condition in JavaScript

How to split an object into array of objects based on a condition. 如何根据条件将对象拆分为对象数组。

oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
          "Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205, 
          "Columbia, SC:Laconia, NH": 0.006360767389277389, 
          "Council Bluffs, IA:Derry, NH": 0.0016636141225441225} 

Above is the given sample object. 上面是给定的示例对象。 I want to make an array of objects like this, 我想制作一个这样的对象数组,

newArray = [{"city":"Chicago", "similarTo":"Myrtle"},
         {"city":"Portsmouth", "similarTo":"Rock Hill"},
         {"city":"Columbia", "similarTo":"Laconia"},
         {"city":"Council Bluffs", "similarTo":"Derry"}]

I have been scratching my head with this for a while now. 我已经为此抓了一段时间了。 How can I get the above array(newArray)? 我怎样才能得到上面的数组(newArray)?

Here is a bunch of code you can try. 这是您可以尝试的一堆代码。

1) Iterate over oldObject and get the name of the property. 1)遍历oldObject并获取属性的名称。

2) Split that name into an array based on the ":" character, since it separates the cities 2)将名称分隔为基于“:”字符的数组,因为它将城市分隔开

3) Go over that new array, splitting it on the "," character (so as not to get the states). 3)遍历该新数组,将其拆分为“,”字符(以免获得状态)。

4) Put the values into the newObject, based on whether it's the first or second part of the original property name. 4)根据是原始属性名称的第一部分还是第二部分,将值放入newObject中。

5) Push that newObject, now with items, into a newArray. 5)将带有项目的newObject推送到newArray中。

Basically, this parses apart the name and does some array splitting to get at the right values. 基本上,这会解析名称,并进行一些数组拆分以获取正确的值。 Hope it helps and helps you understand too. 希望它能对您有所帮助。

 var oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907, "Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205, "Columbia, SC:Laconia, NH": 0.006360767389277389, "Council Bluffs, IA:Derry, NH": 0.0016636141225441225}; var newArray = []; for (object in oldObject) { var thisObjectName = object; var thisObjectAsArray = thisObjectName.split(':'); var newObject = { 'city': '', 'similar_to': '' }; thisObjectAsArray.forEach(function(element,index,array) { var thisObjectNameAsArray = element.split(','); var thisObjectNameCity = thisObjectNameAsArray[0]; if(index===0) { newObject.city = thisObjectNameCity; } else if(index===1) { newObject.similar_to = thisObjectNameCity; } }); newArray.push(newObject); } console.log(newArray); 

PS: to test, run the above code and check your Developer Tools console to see the new array output. PS:要进行测试,请运行上面的代码,然后检查开发人员工具控制台以查看新的数组输出。

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

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