Javascript点缀对象的对象键

时间:2018-03-15 14:58:29

标签: javascript lodash

如何将虚线键转换为javascript对象并保留其值?

所以我从API得到了这种响应,我需要按键解析它:value。

if(img2 != null)

所以我实现了这个目标:

{
  "property": "personal_info.address.city",
  "description": "Missing field"
},
{
  "property": "personal_info.address.country",
  "description": "Missing field"
},

然而,我需要它像这样:

{
    'personal_info.address.city': 'Missing field',
    'personal_info.address.country': 'Missing field'
}

// by using this code (lodash)

_.mapValues(_.keyBy(obj, 'property'), function(o) {
  return o.description;
})

我在stackoverflow中以某种方式搜索如何将点符号字符串转换为对象: Convert string with dot notation to JSON

但是因为我正在改变密钥本身而被困住了。

编辑: 更改了测试城市和测试国家以反映描述字段(抱歉)

2 个答案:

答案 0 :(得分:3)

您可以使用lodash中的_.set

  

设置object path的值。如果var array = [{ property: "personal_info.address.city", description: "Missing field" }, { property: "personal_info.address.country", description: "Missing field" }], object = array.reduce((o, { property, description }) => _.set(o, property, description), {}); console.log(object);的一部分不存在,则创建它。为缺少的索引属性创建数组,同时为所有其他缺少的属性创建对象。使用_.setWith自定义路径创建。

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
import UIKit

class MyList: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    override init(frame: CGRect) {
        super .init(frame: frame)
        setUpLocalizedUserList()

    }


    //Click on User Cell
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Click")

    }


    //Localized User List (Collection View)
    private func setUpLocalizedUserList(){
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: 80)

        let userListFrame = CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: Int(UIScreen.main.bounds.height) - 160)
        let myCollectionView:UICollectionView = UICollectionView(frame: userListFrame, collectionViewLayout: layout)

        myCollectionView.dataSource = self
        myCollectionView.delegate = self
        myCollectionView.register(LocalizedUserCell.self, forCellWithReuseIdentifier: "userCell")
        myCollectionView.register(GroupChatCell.self, forCellWithReuseIdentifier: "groupCell")
        myCollectionView.backgroundColor = UIColor.white

        addSubview(myCollectionView)
    }

    //Number of Section in User List
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }

    //Lists' Sizes
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (section == 0) ? 5 : 4
    }

    //Cells content here
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "userCell", for: indexPath) as! LocalizedUserCell
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "groupCell", for: indexPath) as! GroupChatCell
            return cell
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

答案 1 :(得分:2)

你可以使用forEach()循环和reduce()方法来获得这样的结果。

const data = [{"property": "personal_info.address.city","description": "Missing field"},{"property": "personal_info.address.country","description": "Missing field"}]

const result = {}
data.forEach(function(o) {
  o.property.split('.').reduce(function(r, e, i, arr) {
    return r[e] = (r[e] || (arr[i + 1] ? {} : o.description))
  }, result)
})

console.log(result)