Akebono
V2EX  ›  问与答

JS 中,怎么给 Object 内的所有 Object 添加一个键值对呢?

  •  
  •   Akebono · Feb 17, 2022 · 2869 views
    This topic created in 1743 days ago, the information mentioned may be changed or developed.
    const object = {
        tom:{
            action:{
                eat:()=>{console.log("tom-eat")}
            }
        }
        jerry:{
        	action:{
                eat:()=>{console.log("jerry-eat")}
            }
    	}
        me:{
            action:{
                eat:()=>{console.log("me-eat")}
            }
        }
    }
    

    假设有这么一个 Object ,

    除了遍历和手动输入以外,怎么给这个 Object 内所有的 [key].action 内添加一个 nightshow: [key].action.eat() 键值对呢?

    谢谢!

    11 replies  •  2022-02-18 08:11:08 +08:00
    dcalsky
    dcalsky
    Feb 17, 2022
    1
    js 、ruby 、python 给我最大的感受就是花在思考奇技淫巧上的时间远比老老实实写遍历来得多。
    YouMoeYi
    YouMoeYi
    Feb 17, 2022
    2
    直接整个类, 然后把 tom, jerry, me, 这些 new 出来不行吗
    为啥不考虑遍历, 也没多麻烦
    shintendo
    shintendo
    Feb 17, 2022❤️1
    3
    Object.values(object).forEach(x => x.action.nightshow = x.action.eat())

    这不需要什么奇技淫巧啊
    YouMoeYi
    YouMoeYi
    Feb 17, 2022
    4
    @shintendo 你这把 object 整成数组了吧, key 也丢了
    shintendo
    shintendo
    Feb 17, 2022
    5
    TomVista
    TomVista
    Feb 17, 2022
    6
    Object.prototype.action={eat}
    proger
    proger
    Feb 17, 2022
    7
    [key].action.eat() 把这个没有返回值的空函数赋值过去好像没有意义吧,只能得到 nightshow = undefined
    YouMoeYi
    YouMoeYi
    Feb 17, 2022
    8
    @shintendo 没事 我傻了 传引用 SRY
    Pipecraft
    Pipecraft
    Feb 17, 2022
    9
    用 Proxy 可以做到
    acthtml
    acthtml
    Feb 17, 2022
    10
    可以使用 proxy.
    new Proxy(target, handler)
    gen900
    gen900
    Feb 18, 2022 via iPhone
    11
    for(key in object) object.key.action.nightshow = object.key.action.eat()
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   954 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 19:59 · PVG 03:59 · LAX 11:59 · JFK 14:59
    ♥ Do have faith in what you're doing.