【问题标题】:Modification of array objects数组对象的修改
【发布时间】:2016-04-27 20:56:33
【问题描述】:

我正在尝试重建一个数组,因此我需要有关使用最佳实践的建议。 我有一个数组对象如下:

MainObject:
0:"Namebar"
  1: Object
    Name: "Title1"
    Url: "Url1"
  2: Object
    Name: "Title2"
    Url: "Url2"
  3: Object
    Name: "Title3"
    Url: "Url1"

在上面,因为“url”是相同的,我想将它分组为同一个对象,我期望输出格式如下:

0: "Url1"
  1: Object
    Name : "Title1"
    Url: "Namebar"
  2: Object
    Name : "Title3"
    Url: "Namebar"

1: "Url2"
  1: Object
    Name : "Title2"
    Url: "Namebar"

我试图有两个数组并循环通过 MainObject 来交换项目,我知道这不仅是一个繁琐的过程,而且时间复杂度非常高。 例如像:

var extract1 = MainObject[0];
var extract2 = using for loop to extract and swap ......

我没有任何其他方法可以实现这一目标。在 javascript/jquery 中有什么方法可以解决这个问题?

【问题讨论】:

  • MainObject 中Namebar 的属性名称是什么? MainObject中的数组的属性名是什么@
  • @AlexArt.: Namebar 没有属性名,只有 MainObject[0] 输出为 "Namebar" ,而 MainObject[1] 和 2 是具有上述结构的数组
  • 如何获得嵌套数组?
  • 以文字形式显示 MainObject 数组,而不是文本。
  • var MainObject = new Array(); MainObject.push(name) ;MainObject.push(json 对象);

标签: javascript jquery html arrays


【解决方案1】:

这应该可以完成工作:

var extract1 = MainObject[0];
var newArray = {};
var newArrProp;
var extract1Props = Object.keys(extract1);
for( i = 0; i< extract1Props.length; i++)
{
   newArrProp = extract1Props[i];
   var nestedObjects = extract1[newArrProp];
   for(j = 0; j < nestedObjects.length; j++)
   {
      if(!newArray[nestedObjects[j].Url])
      {
          newArray[nestedObjects[j].Url] = [];              
      }
      newArray[nestedObjects[j].Url].push({Name:nestedObjects[j].Name,Url:newArrProp});
   }
}

Working fiddle

【讨论】:

    【解决方案2】:

    你可以使用一些循环。

    var MainObject = [{ "Namebar": [{ Name: "Title1", Url: "Url1" }, { Name: "Title2", Url: "Url2" }, { Name: "Title3", Url: "Url1" }] }],
        object2 = [];
    
    MainObject.forEach(function (a) {
        Object.keys(a).forEach(function (k) {
            a[k].forEach(function (b) {
                var temp = {};
                if (!this[b.Url]) {
                    temp[b.Url] = [];
                    this[b.Url] = temp[b.Url];
                    object2.push(temp);
                }
                this[b.Url].push({ name: b.Name, Url: k });
            }, this);
        }, this);
    }, Object.create(null));
    
    document.write('<pre>object2 ' + JSON.stringify(object2, 0, 4) + '</pre>');
    document.write('<pre>MainObject ' + JSON.stringify(MainObject, 0, 4) + '</pre>');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2013-05-17
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多