Akebono
V2EX  ›  问与答

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

  •  
  •   Akebono · Feb 17, 2022 · 2356 views
    This topic created in 1546 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
        1
    dcalsky  
       Feb 17, 2022
    js 、ruby 、python 给我最大的感受就是花在思考奇技淫巧上的时间远比老老实实写遍历来得多。
    YouMoeYi
        2
    YouMoeYi  
       Feb 17, 2022
    直接整个类, 然后把 tom, jerry, me, 这些 new 出来不行吗
    为啥不考虑遍历, 也没多麻烦
    shintendo
        3
    shintendo  
       Feb 17, 2022   ❤️ 1
    Object.values(object).forEach(x => x.action.nightshow = x.action.eat())

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