如何从 Javascript 对象中的 属性 路径查找对象值

How to find object value from property path in Javascript object

我用示例说明问题。

例如我有 javascript 个对象。看起来像:

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

我使用深度差异模块找出两个 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]];
}

你可以这样做:

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);

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

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));

披露:我是这两本书的作者 deep-diff and json-ptr

要使用 [ "points", 0, "x" ] 等属性名称数组构建对象,请使用良好的 JSON Pointer 实现,因为它们中的大多数都有转换这些 路径的便捷方法,并将值应用于对象图。

例如 (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" } }