Skip to content Skip to sidebar Skip to footer

How To Find Object Value From Property Path In Javascript Object

I explain the problem with sample. For example i have javascript object. It looks like: var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:'MyName'} } I use dee

Solution 1:

You can use the following logic:

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

Solution 2:

You can use array#reduce and pass your object and path as variables. Array#reduce will return the value corresponding to a path.

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

Solution 3:

You can do like this:

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

Solution 4:

Disclosure: I am the author of both deep-diff and json-ptr.

To build an object out of an array of attribute names such as [ "points", 0, "x" ], use a good JSON Pointer implementation, since most of them have convenience methods for translating these paths, and applying values to object graphs.

For example (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, "  "));

Produces:

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

Post a Comment for "How To Find Object Value From Property Path In Javascript Object"