【问题标题】:Javascript Nested Literal to stringJavascript嵌套文字到字符串
【发布时间】:2014-05-16 00:01:55
【问题描述】:

我正在寻找一种技术来运行嵌套属性的对象并希望加入这些属性。

这是我想加入的对象:

var array = {
  prop1: {
    foo: function() {
      // Your code here
    }
  },
  prop2: {
    bar1: 'some value',
    bar2: 'some other value'
  }
};

结果应该是这样的:

[
  [ 'prop1', 'foo' ],
  [ 'prop2', 'bar1' ],
  [ 'prop2', 'bar2' ]
]

然后我想将数组加入格式如下的字符串:

prop1.foo
prop2.bar1
prop2.bar2

有什么建议吗?

编辑:忘了说它也适用于更深的数组。

【问题讨论】:

  • 任何努力?我们不是来为您生成代码的。我们甚至不是来提供“提示”的,因为这不是帮助台。
  • 我已经尝试了一些代码,但它没有给我想要的结果。你希望我发布我尝试过的内容吗?
  • 另外,您的原始数据结构不是array。这是object
  • @jfriend00 是的,你是对的。我只是忘记了它,因为对我来说很明显我也需要它来处理更深的物体。非常抱歉浪费了您的时间。你有什么建议可以解决我的问题?

标签: javascript arrays join recursion


【解决方案1】:

类似的东西? http://jsfiddle.net/X2X2b/

var array = {
  prop1: {
    foo: function() {
      // Your code here
    }
  },
  prop2: {
    bar1: 'some value',
    bar2: 'some other value'
  }
};

var newA = [],
    newB = [];
for  ( var obj in array ) {
    for  (var inObj in array[obj]) {
        newA.push([obj, inObj]);
        newB.push(obj + '.' + inObj);
    }
}

console.log(newA);
console.log(newB);

【讨论】:

    【解决方案2】:

    这是一个完全不同的问题,因为您已经指定它需要支持任意深度。为了解决这个问题,我们需要使用递归,并且需要使用第二个递归参数来跟踪我们在嵌套层次结构中的位置。

    function objectPropertiesToArrays(obj, prepend) {
      // result will store the final list of arrays
      var result = [];
    
      // test to see if this is a valid object (code defensively)
      if(obj != null && obj.constructor === Object) {
        for (var propertyName in obj) {
          var property = obj[propertyName],
              // clone prepend instantiate a new array
              list = (prepend || []).slice(0);
    
          // add the property name to the list
          list.push(propertyName);
    
          // if it isn't a nested object, we're done
          if (property.constructor !== Object) {
            result.push(list);
    
          // if it is a nested object, recurse
          } else {
            // recurse and append the resulting arrays to our list
            result = result.concat(objectPropertiesToArrays(property, list));
          }
        }  
      }    
    
      return result;
    }
    

    例子:

    var obj = {  
      prop1: {
        foo: function() { }
      },
      prop2: {
        bar1: 'some value',
        bar2: 'some other value'
      },
      prop3: {
        x: {
          y: [],
          z: 'test'
        },
        erg: 'yar'
      }
    };
    
    objectPropertiesToArrays(obj);
    

    返回

    [
      ["prop1", "foo"],
      ["prop2", "bar1"],
      ["prop2", "bar2"],
      ["prop3", "x", "y"],
      ["prop3", "x", "z"],
      ["prop3", "erg"]
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 2011-11-30
      相关资源
      最近更新 更多