最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript reach element by a path array - Stack Overflow

programmeradmin6浏览0评论

I got this path array:

const path = ["a", "b", "c", "d"]

and an object like:

let obj = { "a": { "b": { "c": { "d": 10, "e": 20 } } } }

and I would like to delete that obj["a"]["b"]["c"]["d"] so my obj will be

{ "a": { "b": { "c": { "e": 20 } } } }

I've tried to do some path.forEach looping, appending it but couldn't find a proper way which I appended it as I wish to, so I could access obj to the right place.

I got this path array:

const path = ["a", "b", "c", "d"]

and an object like:

let obj = { "a": { "b": { "c": { "d": 10, "e": 20 } } } }

and I would like to delete that obj["a"]["b"]["c"]["d"] so my obj will be

{ "a": { "b": { "c": { "e": 20 } } } }

I've tried to do some path.forEach looping, appending it but couldn't find a proper way which I appended it as I wish to, so I could access obj to the right place.

Share Improve this question edited Aug 15, 2020 at 12:19 Nick Parsons 50.8k6 gold badges57 silver badges75 bronze badges asked Aug 9, 2019 at 10:22 jezraeljezrael 3714 silver badges13 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 19

You could do this recursively and then use delete to remove the final key-value pair in your base-case:

const path = ["a", "b", "c", "d"]
const obj = { "a": { "b": { "c": { "d": 10, "e": 20 } } } };

const remove_from_path = (obj, [prop, ...rest]) => 
  !rest.length ? delete obj[prop] : remove_from_path(obj[prop], rest);

remove_from_path(obj, path);
console.log(obj);

You can loop through the path array and in each iteration access that property of the obj object. In the last iteration, instead of entering the last property, delete it.

var path = ["a", "b", "c", "d"];
var obj = { "a": { "b": { "c": { "d": 10, "e": 20 } } } };

path.reduce(function(result, key, index) {
  if (index === path.length - 1) delete result[key];
  else return result[key];
}, obj);

console.log(obj);

You could save the last key and reduce the objects to the final object.

const
    remove = (object, [...keys]) => {
        const last = keys.pop();
        delete keys.reduce((o, k) => o[k] || {}, object)[last];
    },
    path = ["a", "b", "c", "d"],
    obj = { a: { b: { c: { d: 10, e: 20 } } } };


remove(obj, path);
console.log(obj);

let obj = { "a": { "b": { "c": { "d": 10, "e": 20 } } } };
const path = ["a", "b", "c", "d"];

const recursiveLookup = (obj) => {
  path.forEach((el) => {
    if(typeof obj[el] === 'object'){
      recursiveLookup(obj[el])
    } else {
      delete obj[el];
    }
  });
};
recursiveLookup(obj);

console.log(obj)

发布评论

评论列表(0)

  1. 暂无评论