如何从JavaScript对象中的属性路径找到对象值



我解释了样本的问题。

例如,我有JavaScript对象。看起来像:

var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }

我使用Deep Diff模块找到两个JSON数组之间的差异。然后找到差异并找到差异路径。如果x的值已更改,则找到。

例如

path = ["points",0,"x"] 
or
path= ["obj","name"]

所以我的问题是如何从这些路径中生成JSON对象。

例如,我必须生成该

trial.points[0].x        or    trial.obj.name  

该怎么做?谢谢您的回答。

您可以使用以下逻辑:

for(var i = 0, result = trial; i < path.length; i++) {
    result = result[path[i]];
}

您可以使用array#reduce并将objectpath作为变量传递。Array#reduce将返回对应于路径的值。

var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} },
    path1 = ["points",0,"x"],
    path2= ["obj","name"],
    valueAtPath = (object, path) => path.reduce((r,p) => r[p], object);
console.log(valueAtPath(trial, path1));
console.log(valueAtPath(trial, path2));

您可以这样做:

var trial= { points:[{x:1,y:2}, {x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"}};
var path = ["points", 0, "x"];
var object = trial;
path.map(field => object = object[field]);
console.log(object);
path = ["obj", "name"];
var object = trial;
path.map(field => object = object[field]);
console.log(object);

披露:我是Deep-Diff和JSON-PTR的作者

用诸如[ "points", 0, "x" ]之类的属性名称构建对象,请使用良好的JSON指针实现,因为它们中的大多数都具有转换这些 paths 的便利方法,并将值应用于对象图。

例如(node.js):

const diff = require("deep-diff");
const ptr = require("json-ptr");
let original = {
  points: [
    { x: 1, y: 2 },
    { x: 5, y: 2 },
    { x: 3, y: 4 }
  ],
  obj: {
    id: 5,
    name: "MyName"
  }
};
let modified = JSON.parse(JSON.stringify(original));
modified.points[0].x = 7;
modified.obj.name = "Wilbur Finkle";
const differences = diff(original, modified);
// Produce an object that represents the delta between original and modified objects
const delta = differences.reduce((acc, record) => {
  // Only process edits and newly added values
  if (record.kind === "E" || record.kind === "N") {
    ptr.set(
      acc, // target
      ptr.encodePointer(record.path), // pointer; from path
      record.rhs, // modified value
      true // force; creates object graph
    );
  }
  return acc;
}, {});
console.log(JSON.stringify(delta, null, "  "));

生产:

{ points: [ { x: 7 } ], obj: { name: "Wilbur Finkle" } }

相关内容

  • 没有找到相关文章

最新更新