如果它们与另一个对象属性匹配,如何在对象中获取值

时间:2019-03-03 23:27:48

标签: javascript json

我在下面有一个要迭代的对象,如果特定对象properties.title与任何其他对象相同,请使用作者姓名并将其添加到新对象中(我以为添加了该对象)到新对象会更容易)。

business1

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -89.535,
                    34.3654
                ]
            },
            "place_name": "University, Mississippi, United States",
            "properties": {
                "title": "Using Adversarial Autoencoders for Multi-Modal Automatic Playlist Continuation",
                "authorTitle": "Florian Mai"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    10.14,
                    54.33
                ]
            },
            "place_name": "24105, Kiel, Schleswig-Holstein, Germany",
            "properties": {
                "title": "Using Adversarial Autoencoders for Multi-Modal Automatic Playlist Continuation",
                "authorTitle": "Iacopo Vagliano"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    10.14,
                    54.33
                ]
            },
            "place_name": "pretend place",
            "properties": {
                "title": "new title",
                "authorTitle": "joe blogs"
            }
        }

    ],
    "properties": "",
    "authors": ""
}

我想要的对象(improvedObj)

var improvedObj = {

    obj1 = {
      title:'Using Adversarial Autoencoders for Multi-Modal Automatic Playlist Continuation"',
      authorList: 'Florian Mai,Iacopo Vagliano'
    },
    obj2 = {
        title:'new title',
        authorList: 'joe blogs
  }

}

我尝试过的

extractorArray = []

for(i=0; i<business1.features.length;i++){
extractorArray.push(business1.features[i].properties)
}
console.log('extractor', extractorArray)

var extractedValues = extractorArray.map((title) => (title));
var extractedAuthor = extractorArray.map((authorTitle) => (authorTitle))

    var improvedObj = {

      objList : {
        title:extractedValues,
        authorList: extractedAuthor
      }
    }

以上内容遍历了每个功能,使用了它的属性并将其推送到extractorArray(这样我就可以在其上使用.map函数)。然后,由于我只是从对象中的数组中复制,所以目前我的想法没有用(如果标题相同,则没有其他内容可以作为作者)。

1 个答案:

答案 0 :(得分:1)

我猜您改进的对象实际上是数组,如果我错了,请纠正我。比跟随应该为您工作

const authorsByBook = k.features.map(feature => feature.properties).reduce((byTitle, feature) => {
    if(!byTitle[feature.title]) byTitle[feature.title] = [];
    byTitle[feature.title].push(feature.authorTitle);
return byTitle
}, {})

const improvedObject = Object.keys(authorsByBook).map(title => ({ title, authorList: authorsByBook[title].join(',')}))

第一部分循环显示槽列表并创建结构为{title:authors []}的对象。之后,基于标题的对象将其分解为包含对象{title,}

的数组