如何编写内联对象属性的函数

时间:2016-06-24 15:43:03

标签: javascript

我有以下对象:

var ob = {
    view: {
        name: 'zpo',
        params: {
            taskId: 3,
            zuka: 'v'
        }
    }
}

我需要以下列形式提供此对象:

{
    "view.name":"zpo",
    "view.params.taskId":3,
    "view.params.zuka":"v"
}

我编写了一个可以做到这一点的函数,但问题是它需要传递给它的外部变量。这是这个功能:

function inline(o, result, container) {
    for (var p in o) {
        if (typeof o[p] === "object") {
            inline(o[p], result.length > 0 ? result+'.'+p : p, container);
        } else {
            container[result + '.' + p] = o[p];
        }
    }
}

var ob = {
    view: {
        name: 'zpo',
        params: {
            taskId: 3,
            zuka: 'v'
        }
    }
}

var c = {};
var r = inline(ob, '', c);

有没有办法编写此函数以返回正确的结果而无需传递resultcontainer外部变量?

3 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望避免使用"空" 参数调用inline()函数。

您可以直接在函数中捕获此案例:

function inline(o, result, container) {
    result = result || '';
    container = container || {};
    ...
}

var r = inline(ob);

对于函数的递归部分,你仍然需要这个参数。

答案 1 :(得分:0)

javascript太棒了!

function inline(o, result, container) {
  result = result || '';
  container = container || {};
  for (var p in o) {
    if (typeof o[p] === "object") {
      inline(o[p], result.length > 0 ? result+'.'+p : p, container);
    } else {
      container[result + '.' + p] = o[p];
    }
  }
}

var r = inline(ob);

答案 2 :(得分:0)

这是一个不需要任何参数的版本。



// Return an array containing the [key, value] couples of an object.
const objEntries = o => Object.keys(o).map(k => [k, o[k]]);

// Create an object from an array of [key, value] couples.
const entriesObj = (entries, init={}) => entries.reduce((result, [key, val]) => {
  result[key] = val;
  return result;
}, init);

// Reduce on the object entries (as returned by objEntries) with an empty object as
// initialiser.
const inline = (o) => objEntries(o).reduce((result, [key, val]) => {
  if(val instanceof Object){
    // If the value is an object, recursively inline it.
    const inlineVal = inline(val);
    // Prefix each property names of inlineVal with the key of val and add the
    // properties to the result object.
    entriesObj(
      objEntries(inlineVal).map(([subK, subVal]) => [key + '.' + subK, subVal]),
      result
    );
  } else {
    // If val is not an object, just add it to the result as is.
    result[key] = val;
  }
  // Return the result.
  return result;
}, {});

var ob = {
    view: {
        name: 'zpo',
        params: {
            taskId: 3,
            zuka: 'v'
        }
    }
}

var r = inline(ob);
console.log(r);




我使用箭头功能和解构。旧浏览器不支持它。如果需要支持它们,只需用常规函数替换箭头函数并手动解构参数。

相关问题