3 回答
TA贡献1826条经验 获得超6个赞
function setTweenedValues(state, values) {
const reducer = (newState, [key, val]) => {
newState[key] = val;
if (typeof val === "number") {
newState[key] = values.shift();
}
if (typeof val === "object") {
newState[key] = Object.entries(val).reduce(reducer, {});
}
return newState;
};
const newState = Object.entries(state).reduce(reducer, {});
return newState;
}
var state = { count: 200, foo: 10, bar: { zzz: 999 }, ignore: "me" },
tweenedValues = [50.1231, 34.43543, 456.4543],
tweenedState = setTweenedValues(state, [...tweenedValues]);
console.log(tweenedState);
TA贡献1824条经验 获得超8个赞
您可以迭代条目并再次为嵌套条目调用该函数。
function setValues(pattern, values) {
return Object.fromEntries(Object
.entries(pattern)
.map(([k, v]) => [
k,
v && typeof v === 'object'
? setValues(v, values)
: values.length ? values.shift() : v
])
);
}
var state = { count: 200, foo: 10, bar: { zzz: 999 }, ignore: "me" },
tweenedValues = [50.1231, 34.43543, 456.4543],
tweenedState = setValues(state, [...tweenedValues]);
console.log(tweenedState);
TA贡献1802条经验 获得超10个赞
如我所见,您在数组中的值始终处于保证顺序,并且您希望它们作为对象中的道具值...您可以使用对象解构
const [count, foo, bar] = tweenedValues;
然后像这样制作对象
let obj = {count, foo, bar}
添加回答
举报