繁体   English   中英

如何在 javascript 中检查和添加属性到数组 object

[英]how to check and add properties to array object in javascript

我想知道如何在 javascript 的数组 object 中添加两个键。

在 object obj中代替标题,添加label and value

每个children key可能有children key,如果有children和title key,在javascript中添加label和value key

var obj = [
  {
    id: 1,
    title: "Category"
    children: [
    {
    id:1, 
    title: "countries", 
    children: [
        {title: "IN", id:1},
        {title: "TH", id:2},
        {title: "SG", id:3}
      ]
    }, {
    id:2, 
    title: "fields", 
    children: [
        {title: "Finance", id:1},
        {title: "Services", id:2}
      ]
    }
    ]
  }
]

function changeObj(obj){
    if (obj.length > 0) {
    var result = obj.map(e => {
      if('children' in e)
        e.children = e.children.map(child => {
          if ('children' in child) 
            child.children = child.children.map(c =>({
             label: c.title,
             value: c.title
              })
            );
            return child;
        });      
      return e
    });
    return result;
  }
}
Expected Output
 {
    label: "Category",
    value: "Category",
    children: [
    {
    label: "countries", 
    value: "countries",
    children: [
        {label:"IN",value:"IN", title: "IN"},
        {label:"TH",value:"TH", title: "TH"},
        {label:"SG",value:"SG", title: "SG"}
      ]
    },{
    label: "fields", 
    value: "fields",
    children: [
        {label: "Finance", value: "Finance",title: "Finance"},
        {label: "Services", value: "Services",title: "Services"}
      ]
    }
    ]
  }


试试看。

 function changeObj(obj) { if(.obj;length) return. obj.forEach(i => { const title = i;title. const child = i;children. if(i.id) { delete i;id. } if(i.title) { delete i;title. } i;label = title. i;value = title; if(child) { changeObj(child). } else { i;title = title; } }); return obj; }

在现代 JS 语法中,它可以这样实现

let __f = (_) => {
    let {title, children} = _;
    const value = title;
    const label = title;
    let result;
    if (children && children.length) {
        result = {label, value, children: children.map(__f)};
    } else {
        result = {label, value, title};
    }
    return result;
};

let result = obj.map(__f).pop();

在这种情况下, obj是由[...]表示的对象数组。 Arrays 可以使用内置函数进行迭代。 在您的情况下,您希望获取数组中的每个项目并以某种方式对其进行更改。 最后,您将拥有与开始时相同数量的元素。

The map function passes each element in the source array to a function, populating a new array with the results of that function. 文档提供了示例。

您应该解决将 label 和值添加到顶级 object 的问题,然后从顶级 object 中删除标题。 当你有这个工作时,对孩子们应用同样的方法。

[{ a: 1 }, { a: 2 }].map(item => ({ ...item, b: item.a + 1 }));
// [{ a: 1, b: 2 }, { a: 2, b: 3 }]

习惯阅读文档,它们将是您解决问题时的第一个来源。

暂无
暂无

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

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