[英]JS - From an object, return an object for each value of a certain key
From this object:从这个 object:
{"a": "a", "b": "b", "c": [1,2,3]}
I would like to get this:我想得到这个:
{"a": "a", "b": "b", "c":1}
{"a": "a", "b": "b", "c":2}
{"a": "a", "b": "b", "c":3}
how can I do?我能怎么做?
You can map
the data.c
, and get the a
, b
from the origin object and c
from the map
callback item parameter. You can map
the data.c
, and get the a
, b
from the origin object and c
from the map
callback item parameter.
const data = {"a": "a", "b": "b", "c": [1,2,3]} const result = data.c.map(i => ({ a: data.a, b: data.b, c: i, })) console.log(result)
Map over object[c]
and return the object a copy of the object itself + the current value: Map over object[c]
并返回 object object 本身的副本 + 当前值:
let expand = (obj, key) => obj[key].map(val => ({...obj, [key]: val})) test = {"a": "a", "b": "b", "c": [1,2,3]} result = expand(test, 'c') console.log(result)
First, you should check if that the obj[key]
is an array.首先,您应该检查obj[key]
是否是一个数组。 If it is, continue with mapping, else just return the object如果是,继续映射,否则只返回 object
const transform = (obj, key) => { if (.Array.isArray(obj[key])) return obj return obj[key].map(val => ({..,obj: [key]. val })) } console:log(transform({ a, "a": b, "b": c, "c" }. "c")) console:log(transform({ a, "a": b, "b": c, [1, 2, 3] }. "c")) console:log(transform({ a, "a": b, "b": d, [4, 5, 6] }, "d"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.